【问题标题】:Images Not Updating In Swing图像未在 Swing 中更新
【发布时间】:2013-05-17 12:44:22
【问题描述】:

我在我的 GUI 中更新图像时遇到问题。除了这些方法之外的所有内容都被正确编码,因为当我在 GUI 的初始化中编写代码(来自下面的“setImage”方法)时会出现图像。

我正在尝试获取单击按钮时更新图像的方法。但是,当单击按钮时,没有任何变化。方法调用正确地写入了 MouseListener。所有的 JLabels / Images 都被声明为私有的,所以我可以在方法中调用它们。

public void setImage(String path) {

    //path = "imageName.png"
    removeImageLabel();
    try {
        img = ImageIO.read(new File(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
    imageLabel = new JLabel(new ImageIcon(img));
    imagePanel.add(imageLabel);
    imagePanel.repaint();
}

public void removeImageLabel() { //removes the current image from the GUI
    imagePanel.remove(imageLabel);
}

我还有其他方法可以根据按钮点击来设置元素,但这似乎不起作用。没有错误被抛出,但没有任何更新。怎么了?

注意:我在方法中添加了一个 println() 并调用它。

新功能: 我在创建 GUI 时添加了一个图像,它会显示出来,但在调用方法时它永远不会被删除。

【问题讨论】:

  • 您是否尝试在您的setImage 方法中添加一些System.out.println() 以查看它是否被调用?

标签: java image swing repaint imageicon


【解决方案1】:

不要替换整个图像组件,而是考虑更新组件的图像,如example所示,或更新标签的图标就位,如图here

【讨论】:

    【解决方案2】:

    调用validate() 而不是repaint()

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 2017-10-31
      相关资源
      最近更新 更多