哪个语句清除了之前的Graphics并在Java中绘制了一个新的One?

Which statement clears the previous Graphics and draw a new One in Java?

这是代码:

public void paint(Graphics g) {
    g.fillOval(x, y, 25, 25);

    repaint();

}

这将创建一个类似 This 的输出,如果我移动指针,它不会清除以前的图形并创建一个路径。

Output of Above Code

并且通过添加这样的 super 语句,它不会显示路径,只会显示椭圆图形的当前位置。

public void paint(Graphics g) {
    super.paint(g);
    g.fillOval(x, y, 25, 25);

    repaint();

}

The output is This

我只想了解其背后的机制和原因。

抱歉,您的代码有很多错误,我们必须修复它:

  • 首先,不要覆盖 JComponent(或 JFrame)的绘制方法,而是覆盖 JComponent 或 JPanel 的 paintComponent。通过这种方式,您可以避免错误地弄乱边界或子组件的绘制,这两者都是绘制负责的。另外由于 paintComponent 有自动双缓冲,你的动画会更流畅。
  • 接下来,您几乎总是想要调用 super 的绘画方法,对于 paintComponent 来说是 super.paintComponent(g) 因为这将继续传播绘画链,而不调用它会破坏该链。调用 super 的方法将调用组件的内务处理绘画,包括 "dirty" 像素的过度绘画,这就是删除轨迹的原因。这可能是您正在寻找的答案。
  • 最重要的是从不从任何绘画方法中调用repaint()。这样做会导致完全无法控制的穷人动画,并将过多的责任放在本应专注于其唯一工作——绘制组件的绘制方法上。请改用 Swing Timer 等游戏循环。

最重要的 -- 阅读教程,因为大部分内容已经在其中进行了解释:

直接来自 docs

public void paint(Graphics g)

Paints the container. This forwards the paint to any lightweight components that are children of this container. If this method is reimplemented, super.paint(g) should be called so that lightweight components are properly rendered. If a child component is entirely clipped by the current clipping setting in g, paint() will not be forwarded to that child.

正如他所说,super.paint() 会清除脏像素。这说明了一切。 :)