简体   繁体   中英

Java adding image to JPanel. Why is the image not showing?

I'm pulling my hair out on this one. Many questions like this here on SO, but I can't get it to work.

I'm trying to add an image to an existing JPanel. The problem is getting the image to be visible in the JPanel. The code runs, but the image is nowhere..

Here's my code:

private void loadImgBtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:      
    int returnVal = fileChooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION)
    {

        File file = fileChooser.getSelectedFile();
        BufferedImage myPicture = null;
        try {
            myPicture = ImageIO.read(file);
        } catch (IOException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        JLabel picLabel = new JLabel(new ImageIcon(myPicture));
        imagePnl2.add(picLabel);
        imagePnl2.repaint();
        imagePnl2.revalidate();

    }
    else
    {
        System.out.println("File access cancelled by user.");
    }

}

In this question the problem was the missing revalidate() . But that makes no difference here.

What am I missing?

In this question the problem was the missing revalidate(). But that makes no difference here.

Order is important. The code should be:

panel.add(...);
panel.revalidate();
panel.repaint();

The revalidate() invokes the layout manager which in turn determines the components size and location. By default components have a size of (0, 0) so if you invoke repaint() first there is nothing to paint.

Also, an easier solution would be to just add an empty label to your panel when you create the GUI. Then when you want to add the image you can just do:

label.setIcon(...);

The setIcon() method automatically does the revalidate() and repaint() for you.

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