Java 为什么paintComponent会多次绘制圆?

Java 为什么paintComponent会多次绘制圆?,java,Java,我需要使一个圆看起来像是在反弹,但我得到的输出是许多圆,而不是只有一个在移动。如何使“paint component”在动画期间仅绘制一个圆,而不是在移动时向我显示几个球 class thePanel extends JPanel { int radius; int diameter; int x; int y; int dx; int dy; int timerInterval = 10; Timer timer; thePan

我需要使一个圆看起来像是在反弹,但我得到的输出是许多圆,而不是只有一个在移动。如何使“paint component”在动画期间仅绘制一个圆,而不是在移动时向我显示几个球

class thePanel extends JPanel {
    int radius;
    int diameter;
    int x;
    int y;
    int dx;
    int dy;
    int timerInterval = 10;
    Timer timer;

thePanel() {
    x = 0;
    y = 0;
    dx = 3;
    dy = 3;
    radius = 20;
    diameter = radius * 2;
    timer = new Timer(timerInterval, new TimerListener());
    timer.start();
    repaint();
}

protected void paintComponent(Graphics g) {
    super.paintComponents(g);
    g.drawRect(getWidth() / 2, 0, getWidth() / 2, getHeight());
    g.drawOval(this.x - radius, this.y - radius, diameter, diameter);
}

public void fixPosition() {
    x += dx;
    y += dy;
    if (x < radius)
        dx = Math.abs(dx);
    if (x > getWidth() - radius) 
        dx = -Math.abs(dx);
    if (y < radius) 
        dy = Math.abs(dy);
    if (y > getHeight() - radius) 
        dy = -Math.abs(dy);
}

class TimerListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
       fixPosition();
       repaint();
    }
   }
}
class thePanel扩展了JPanel{
整数半径;
内径;
int x;
int-y;
int-dx;
int-dy;
int timerInterval=10;
定时器;
thePanel(){
x=0;
y=0;
dx=3;
dy=3;
半径=20;
直径=半径*2;
计时器=新计时器(timerInterval,new TimerListener());
timer.start();
重新油漆();
}
受保护组件(图形g){
超级组件(g);
g、 drawRect(getWidth()/2,0,getWidth()/2,getHeight());
g、 drawOval(这个.x-半径,这个.y-半径,直径,直径);
}
公共无效固定位置(){
x+=dx;
y+=dy;
if(x<半径)
dx=Math.abs(dx);
如果(x>getWidth()-radius)
dx=-Math.abs(dx);
if(y<半径)
dy=Math.abs(dy);
如果(y>getHeight()-radius)
dy=-Math.abs(dy);
}
类TimerListener实现ActionListener{
@凌驾
已执行的公共无效操作(操作事件e){
固定位置();
重新油漆();
}
}
}

它看起来像一个打字错误,请尝试
super.paintComponents(g)
而不是
super.paintComponents(g)
。如何清除它?使用
g.setColor()清除背景;g、 drawRect()
。覆盖整个区域。哈哈!真的@Arnaud!非常感谢。paint、paintcomponent和paintcomponent之间的区别:它看起来像一个打字错误,请尝试
super.paintcomponent(g)
而不是
super.paintcomponents(g)
。我应该如何清除它?使用
g.setColor()清除背景;g、 drawRect()
。覆盖整个区域。哈哈!真的@Arnaud!非常感谢。油漆、油漆组件和油漆组件之间的区别: