图像不会显示在JLabel中

时间:2013-05-08 09:43:58

标签: java image swing user-interface jlabel

我使用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);
    }
}    

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

1 个答案:

答案 0 :(得分:0)

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