【问题标题】:Update a JLabel with a JButton使用 JButton 更新 JLabel
【发布时间】:2013-10-22 07:12:14
【问题描述】:

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

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

提前致谢。

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

【问题讨论】:

标签: jbutton jlabel bufferedimage


【解决方案1】:

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

我希望这对将来的某些人有用!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 2020-06-26
    相关资源
    最近更新 更多