使用JButton更新JLabel

时间:2013-10-22 07:12:15

标签: jbutton jlabel bufferedimage

在我的代码中,我有一个JButton(名为PlotStatus),当单击它时,在JLabel内部导入并打印一个图像。图像从不断更新的png文件导入为BufferedImage。我希望能够在点击JButton的任何时候刷新/更新JLabel上的图像。也就是说,在每次单击时我都希望缓冲区内存重置并且JLabel重新加载(更新的)图像。相反,我会打印出所有不同的图像,第一个保留在前景中。

StatusLabel和temp在这里定义为私有(但公开没有区别)。 我已经尝试了很多不同的方法,并且阅读了许多绝对没有运气的帖子,因为它看起来应该有效。任何建议都非常感谢。

提前致谢。

        //This is an Item Listener which reacts to clicking on the JButton PlotStatus
    PlotStatus.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ev) {

    JLabel statusLabel = new JLabel(); panel1.remove(statusLabel);
    BufferedImage bufferedImage = null;
    try {   
    bufferedImage = ImageIO.read(new File("status.png"));
    bufferedImage.flush();

    JLabel temp = new JLabel();
    temp.setIcon(new ImageIcon(bufferedImage));
    statusLabel = temp;
    panel1.add(statusLabel);    
    revalidate();repaint();

    statusLabel.setVisible(true);statusLabel.setBounds(560,20,650,440); 
    } catch(IOException ex) {ex.printStackTrace();}
     }
    });

1 个答案:

答案 0 :(得分:0)

所以,我自己找到了答案。愚蠢的是,我在ActionListener中有JLabel statusLabel = new JLabel(); 。所以,每当我点击按钮时,触发的动作都会创建JLabel的新实例(因此BufferedImage),导致我的挥杆数量等于点击次数的JLabel的JButton!我只是在行JLabel statusLabel = new JLabel();之前移动了PlotStatus.addActionListener(new ActionListener() {,它现在可以正常工作,并按照预期更新每次点击的BufferedImage。

我希望这对将来有人有用!