Search code examples
javaswinganimationpaintcomponent

Animation doesn't work as expected


I want to make a rectangle move and it moves but the Rectangle gets bigger while moving. (I don't have 10 reputations to show you a screen shot)

I really don't know what I did wrong, here is my source code:

Class Paddle.java

package ma.Game;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.Timer;

public class Paddle extends JPanel implements ActionListener{

int x = 0, velX = 2;
Timer t = new Timer(5, this);

public Paddle() {
    // TODO Auto-generated constructor stub
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponents(g);

    g.setColor(Color.BLACK);
    g.fillRect(x, 30, 50, 30);

    t.start();
  }

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    x = x + velX;
    repaint();
}
}

Class Frame.java Where I add the panel to my Frame.

    package ma.Game;


import javax.swing.JFrame;

public class Frame extends JFrame
{
    public Frame() {
        // TODO Auto-generated constructor stub
        setTitle("Game");
        setSize(300, 500);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        add(new Paddle());
    }
}

Solution

  • You're calling

    super.paintComponents(g);
    

    which causes painting from previous calls to paintComponent to remain visible. Instead use

    super.paintComponent(g);
    

    which repaints the background of the container