1

I need to make a circle look like it is bouncing but the output I get is many circles instead of only one moving. How can I make paint component only draw one circle during the animation instead of showing me several balls as it moves?

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();
    }
   }
}
yara raffoul
  • 93
  • 1
  • 11

0 Answers0