0

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.

Fred
  • 169
  • 1
  • 3
  • 19

1 Answers1

0

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.

Drewll
  • 318
  • 2
  • 10
  • Thanks Drewll but in Eclipse I have this error : "The method revalidate() is undefined for the type Container". Indeeed, contenant is a container : private Container contenant;. – Fred Aug 20 '16 at 10:39
  • I created a JPanel to use revalidate() method. Thanks for your help. – Fred Aug 20 '16 at 11:07