Home > database >  I can't display an image in a panel
I can't display an image in a panel

Time:05-28

I'm trying to display an image in a JPanel in an application where I already did that in another panel. So the first thing I did it was to use the same code but it didn't work!

I got this message:

javax.imageio.IIOException: Can't read input file!

So did some Google search and I got the following example from Youtube:

package MainFrame
import all as required

public class ExImage {

  ExImage()
  {
  try 
  {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JPanel Example");

    JPanel panel = new JPanel();
    panel.setBounds(50, 50, 250, 250);
    BufferedImage image = ImageIO.read(new File("about.png"));
    JLabel label = new JLabel(new ImageIcon(image));
    panel.add(label);

    // main window
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // add the Jpanel to the main window
    frame.add(panel); 
    frame.setSize(400, 400);
    frame.setLayout(null);
    frame.pack();
    frame.setVisible(true);
  } 
  catch (IOException e) {
  e.printStackTrace();
  }

  }

I copied it because in the video it worked well. But surprisingly when I test it I got the same error! Of course, the path is right, so I don't understand why the code doesn't find the image.

CodePudding user response:

I use code like this - just watch out I load the image from the classpath:

public class App extends javax.swing.JFrame {
    private final javax.swing.ImageIcon iiFound = new javax.swing.ImageIcon(getClass().getResource("/images/done_outline_FILL0_wght400_GRAD0_opsz48.png"));

    ...
    JLabel myLabel = new JLabel();
    myLabel.setIcon(iiFound);
    ...

With this I can initialize the UI with a specific icon, but I also can replace the image at runtime, e.g. from an ActionListener attached to a JButton.

  • Related