JAVA - 添加图像到 JPanel

JAVA - Add an image to JPanel

我是 JAVA 的新人。 我想在我的 window (JPanel) 中获取一张图片用于处理它(例如添加圆圈)。 我创建了一个菜单,当我单击 "File>Import" 时,出现打开的对话框以选择我的图像。我得到了图像文件的正确路径(感谢 System.out.println(FC.getSelectedFile().toString());)但是图像没有出现...

这是代码:

        //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();
              }
          });

感谢您的支持。

替换为:

contenant.repaint();

有了这个:

contenant.revalidate();

当您添加 JLabel 时,它不会自动强制内容窗格整理它的布局,因此即使 JLabel 在那里,它还没有调整大小。调用 revalidate() 解决了这个问题。