Java不必要的图像覆盖
你好,Java开发人员
到目前为止,我从未遇到过这种情况。这个场景是:
(为了使场景更具一般性,让我们来看一下这个例子。)
我们已经声明了Box.png
和Circle.png
:
private final URL IMG1_DIRECTORY = Main.class.getResource("/res/Box.png");
private final URL IMG2_DIRECTORY = Main.class.getResource("/res/Circle.png");
在我们的建造商下:
try {
box = ImageIO.read(IMG1_DIRECTORY);
} catch (Exception e) {
// Our catchblock here
}
try {
circle= ImageIO.read(IMG2_DIRECTORY);
} catch (Exception e) {
// Our catchblock here
}
currentImg = box;
使用paint
方法,框被绘制到我们的JPanel
,如我们的Illustration 1
中所示
@Override
public void paint(Graphics g) {
g.drawImage(currentImg, DEFAULT_LOCATION, DEFAULT_LOCATION, null);
}
通过某个事件,mousePressed
在本例中,图像将被更改
@Override
public void mousePressed( MouseEvent e ) {
currentImg = circle;
repaint();
}
所需的输出显示在我们的Illustration 2
中。不幸的是,结果恰好是Illustration 3
问题是:
-为什么结果恰好是两个图像相互重叠
-另一件事,如果我有一个将图像重新绘制为圆形(从Illustration 3
)的代码,该框将只覆盖circle
图像
# 1 楼答案
重写
paintComponent()
(不是paint()
方法)调用
super.paintComponent(g)
# 2 楼答案
super.paint
,除了一大堆其他重要内容外,它还清除了图形上下文paint
,通常最好使用paintComponent,但请确保调用super.paintComponent
图形上下文是一个共享资源,并且往往在重新绘制之间重复使用,这意味着,因为在绘制时没有清除图形上下文,所以您得到了以前的“状态”,然后重新绘制
# 3 楼答案
你需要重新粉刷屏幕。Java会继续痛苦,直到您告诉它不要或告诉它重新启动
super.paintComponent(g);
将允许此重置。或者,你需要在你想要空白的部分上重新画一个正方形
g.clearRect(x,y,width,height)
只需清除左上角为x,y的矩形
更新此代码
考虑到这些变化。你也应该超越这个组件