【问题标题】:JPanel background image not getting changedJPanel 背景图像没有改变
【发布时间】:2013-03-11 08:38:27
【问题描述】:

我正在使用以下类将背景图像添加到 JPanel。

http://www.java2s.com/Code/Java/Swing-JFC/Panelwithbackgroundimage.htm

但是当应用程序正在执行并更改图像时,新的更新图像不会显示在屏幕上。

    Image image = new ImageIcon(path + item.getItemID() + ".png").getImage();
    panel = new ImagePanel(image);

变量路径是工作区外的静态路径。

【问题讨论】:

  • 在图像更改后尝试panel.repaint()。还有,怎么换头像?你在创建一个新的 ImagePanel 吗?
  • 对此进行了尝试,也尝试使用新的 JPanel 更新 JPanel。但得到相同的旧图像。在油漆中手动更改图像
  • 此外,如果从路径中删除图像,应用程序会将图像显示到 JPanel 背景

标签: java image swing jpanel paintcomponent


【解决方案1】:

如果您“使用新的 JPanel 更新 JPanel”,您并不是在“更新”,而是在创建一个新的 JPanel。 例如,我们有一个名为“panelTest”的绿色 JPanel:

panelTest = new JPanel();
panelTest.setBackground(Color.green);
add(panelTest);

现在我们有了一个按钮,可以将 JPanel 背景颜色从绿色更改为红色,但是方式错误:

JButton btnTest = new JButton("Test");
btnTest.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        panelTest = new JPanel(); //woops, now we have 2 panels...
        panelTest.setBackground(Color.red);
    }
});

请注意,panelTest 是一个指向绿色面板的指针,现在它指向一个带有红色背景的新 JPanel。这个新的 JPanel 尚未添加到任何容器中,因此不会显示。旧的绿色面板将保持可见。

更新图像的最佳方法是在 ImagePanel 中创建一个方法,例如:

public void setImage( Image image ) {
    this.img = image;
    this.repaint();
}

这样你就不必为了改变背景而创建一个新的 ImagePanel。

【讨论】:

  • 我不仅在创建新的 JPanel,而且父框架 JInternalFrame 也是新的。
  • ok @Kidaaaa 为什么不分享一些代码让我们看看问题出在哪里?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多