简体   繁体   中英

Resizing JFrame to fit JPanel

I have a GUI, which consists of a JFrame and Menu bar. Inside the JFrame is my custom Panel (extending JPanel), which is initially hidden. The user chooses an image (JFileChooser), this image is passed to the panel and drawn (using paintIcon). The panel is resized to fit the image and then set visible. I want to resize my JFrame to fit the panel, but I cannot seem to get it to work. I have tried using the pack() method, but this just makes a tiny GUI, that is the size of the JMenu! I have also tried resizing both the frame and the JPanel using the getIconWidth() and getIconHeight() properties of the ImageIcon, but while this correctly sizes the panel it does not size the JFrame. Any ideas as to how I would do this correctly?

The block of code where I am setting the size of the JFrame is here:

@Override
public void actionPerformed(ActionEvent e) 
{

    JFileChooser imgChooser = new JFileChooser();
    JMenuItem evtSource = (JMenuItem) e.getSource();
    String srcText = evtSource.getText();

    if (srcText.equals("Add Image..."))
    {
        imgChooser = new JFileChooser();
        imgChooser.showOpenDialog(frmMain);

        chosenImage = imgChooser.getSelectedFile();
        try
        {
            loadedImage = ImageIO.read(chosenImage);
        }
        catch (IOException ex)
        {
            String errorMsg = ex.getMessage();
            JOptionPane.showMessageDialog(frmMain, "Error while loading file: " + errorMsg, "Error!", JOptionPane.ERROR_MESSAGE);
        }

        panelImage = new ImageIcon(loadedImage);

        frmMain.setSize(panelImage.getIconWidth(), panelImage.getIconHeight() + mbMenu.getHeight());
        displayImage.loadImage(panelImage);
        displayImage.setVisible(true);

    }
}

The code from the relevant sections of the "displayImage" custom panel is below:

public void paintComponent(Graphics g) 
{
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;

        if (imgIsLoaded)
        {
            panelImage.paintIcon(this,g2,0,0);
            resizePanel(panelImage.getIconWidth(), panelImage.getIconHeight());

        }
}

public void loadImage(ImageIcon i)
{
    panelImage = i;
    imgIsLoaded = true;
}

public void resizePanel(int w, int h)
{
    this.setSize(w, h);
}

Override getPreferredSize() in the panel to return a default value (eg 400x400) if it has no image, and the size of the image otherwise.

After setting an image, call frame.pack() .

BTW - if all the panel does is paint the image, I'd opt for a JLabel instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM