0

我使用 NetBean 的内置 GUI 构建器创建了一个 Gui,现在我正在尝试添加允许用户选择图像的代码,该图像应该显示在 A JLabel 中的 ImageIcon 中,但我无法显示图像。

  private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {                                      
     CardLayout cl = (CardLayout)(mainPanel.getLayout());         
     cl.show(mainPanel, "uploadImage" );

     File im1 = null;
     JFileChooser chooser = new JFileChooser();
     FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "JPG, GIF, PNG Images", "jpg", "gif", "png");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(mainPanel);

    try {
        if(returnVal == JFileChooser.APPROVE_OPTION) {       
                im1 =  chooser.getSelectedFile();
        }
        else {
            throw new IOException();
        }
        BufferedImage buff = ImageIO.read(im1);

        BufferedImage resizedImage = new BufferedImage(imagePanel.getWidth(), imagePanel.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(buff, 0, 0, imagePanel.getWidth(), imagePanel.getHeight(), null);
        g.dispose();          

        JLabel picLabel = new JLabel(new ImageIcon (resizedImage));
        picLabel.setVisible(true);

        imagePanel.add(picLabel);// this is the Jpanel that should displpay the image 
        this.validate(); // this refers to the frame that holds all of the components
    } catch (IOException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}    

我已经尝试在框架和包含图像图标的面板上进行验证和重新验证,但似乎没有任何效果。任何帮助是极大的赞赏。

4

1 回答 1

0

添加图像后,您可以尝试 repaint() 方法。

于 2013-05-08T10:11:29.913 回答