Mic*_*dan 2 java swing image paint paintcomponent
你好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");
Run Code Online (Sandbox Code Playgroud)
在我们的构造函数下:
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;
Run Code Online (Sandbox Code Playgroud)
使用该paint方法,框被绘制到我们的JPanel,如我们所示Illustration 1.
@Override
public void paint(Graphics g) {
g.drawImage(currentImg, DEFAULT_LOCATION, DEFAULT_LOCATION, null);
}
Run Code Online (Sandbox Code Playgroud)
通过某个事件,mousePressed在此示例中,图像将被更改.
@Override
public void mousePressed( MouseEvent e ) {
currentImg = circle;
repaint();
}
Run Code Online (Sandbox Code Playgroud)
所需的输出显示在我们的Illustration 2.不幸的是,结果恰好是Illustration 3.
问题是:
- 为什么结果恰好是两个图像相互叠加?
- 另一件事,如果我有一个代码将图像重新绘制为圆形(从Illustration 3)该框将只覆盖circle图像.

super.paint,除了一大堆其他重要的东西,它还清除了图形上下文paint,通常首选使用paintComponent,但请确保调用super.paintComponent图形上下文是一个共享资源,往往会在重绘之间重复使用,这意味着,因为您在绘制时没有清除图形上下文,所以您已经获得了之前的"状态",然后将其绘制