My custom JDialog appears minimized and JScrollPan

2019-08-28 20:36发布

问题:

I have created a basic swing program which displays an image in a JDialog box after it has been selected through a JFileChooser. I have used a JScrollPane inside the dialog box and a JLabel on which image is added as an icon, inside the pane.

The following is the code I have used to construct the dialog box and its contents, the objects are already initialized with a simple new call:

    jDialog1.setTitle("Image");
    jDialog1.setModal(true);

    jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jScrollPane2.setViewportView(jLabel1);

Netbeans has been used to build the GUI.

The following is the code I have used to load and display the image:

    int rval = jFileChooser1.showDialog(this, "Show");
    File f = jFileChooser1.getSelectedFile();
    jDialog1.setTitle(jDialog1.getTitle() + " : " + f.getName());
    try {
        BufferedImage bf = ImageIO.read(f);
        jLabel1.setIcon(new ImageIcon(bf));
    }
    catch (IOException ioe) {
    }
    jDialog1.setLocationRelativeTo(null);
    jDialog1.setVisible(true);
    jDialog1.pack();

Though the image is loaded and displayed, the trouble is

  • My dialog box appears in a minimized form in the upper left hand corner and i have to drag its corner to view the image. Including an image of the same.

  • The horizontal scroll of the scroll pane disappears long before the dialog box is fully extended and the image is fully displayed. Though the vertical scroll bar acts fine.

I have tried setting size and preferred size of both JDialog and JLabel but the problems still persist.

Thanx in advance!

Note: The horizontal scroll bar problem is solved by using the pack() method on the dialog box but the minimized dialog box is still there. Also, the dialog box now appears in the center of the screen as well.

回答1:

Sequence of method calls matters for modal dialogs, you must call the pack before making the dialog visible (because otherwise the pack wouldn't be executed before the dialog is closed):

dialog.pack();
// Edit: manually double its size:
dialog.setSize(dialog.getPreferredSize().width * 2, dialog.getPreferredSize().height * 2);
dialog.setVisible(true);