Fred Fred - 3 months ago 20
Java Question

JAVA - Add an image to JPanel

I'm new in JAVA.
I would like to get an image in my window (JPanel) for working on it (add circles for example).
I created a menu and when I click in "File>Import", the open dialog box is appearing to choose my image. I get the right path to the image file (checked thanks to System.out.println(FC.getSelectedFile().toString());) but the image doesn't appear...

Here is the code :

//On crée les listeners pour le menu "Fichier" :
this.importer.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
//On ouvre la boîte de dialogue pour charger le dessin :
JFileChooser FC = new JFileChooser();
FC.showOpenDialog(null);
BufferedImage myPicture=null;
try {
myPicture = ImageIO.read(FC.getSelectedFile());
System.out.println(FC.getSelectedFile().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
contenant.add(new JLabel(new ImageIcon(myPicture)), BorderLayout.CENTER);
contenant.repaint();
}
});


Thanks for your support.

Answer

Replace this:

contenant.repaint();

With this:

contenant.revalidate();

When you add the JLabel, it doesn't automatically force the content pane to sort out it's layout, so even though the JLabel is on there, it's not sized yet. Calling revalidate() fixes this.

Comments