Java不必要的图像叠加

Mic*_*dan 2 java swing image paint paintcomponent

你好Java开发人员,

到目前为止,我从未遇到过这种情况.这个场景是:(

为了让读者能够使用这个场景,请举例说明.)

我们有这个Box.pngCircle.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图像.

在此输入图像描述

Sta*_*avL 6

覆盖paintComponent()(不是paint()方法).

呼叫 super.paintComponent(g)


Mad*_*mer 6

  1. 你没有打电话super.paint,除了一大堆其他重要的东西,它还清除了图形上下文
  2. 您应该极度需要覆盖paint,通常首选使用paintComponent,但请确保调用super.paintComponent

图形上下文是一个共享资源,往往会在重绘之间重复使用,这意味着,因为您在绘制时没有清除图形上下文,所以您已经获得了之前的"状态",然后将其绘制

  • @MichaelArdan paint调用paintComponent,paintBorder和paintChildren,通过覆盖绘制,你基本上剥离了实际渲染其所有图层的组件功能.Paint还设置了双缓冲,这将防止更新闪烁 (2认同)