Search code examples
javagraphics2d

my repaint(); does not clear previously drawn objects


Hello I am trying to code a simple program that lets me move a rectangle around on a JFrame, my problem is that instead of moving the rectangle around it draws a new one leaving the other one behind and I do not know why this is happening, would love some help here is my current code for the drawing class:

public class frameUpdater extends JPanel implements ActionListener {

private Timer FPS;
private int frameDelay = 40;
private int xVal = 50;
private int yVal = 50;
private int SQUARE_SIZE = 30;

public frameUpdater() {
    FPS = new Timer(frameDelay, this);
    FPS.start();
}
@Override
public void paintComponent(Graphics g) {
    super.paintComponents(g);
    g.setColor(Color.GREEN);
    g.fillRect(xVal,yVal,SQUARE_SIZE,SQUARE_SIZE);


}

public void actionPerformed(ActionEvent e) {
    xVal += 5;
    repaint();
    System.out.println("updated");
}
}

And here is my code for my main class:

public class mainEngine {

public static void main(String[] args) {
    int FRAME_WIDTH = 500;
    int FRAME_HEIGHT = 400;

    frameUpdater s = new frameUpdater();
    JFrame mainFrame = new JFrame();

    mainFrame.setBackground(Color.BLACK);
    mainFrame.add(s);
    mainFrame.setVisible(true);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setSize(FRAME_WIDTH,FRAME_HEIGHT);

}

Very thankful for any help or tips that I can get.


Solution

  • my repaint(); does not clear previously drawn objects

    Always look to see if you are appropriately calling the super's painting method and in the right place when something like this happens since your painting method must call the appropriate super's method for dirty bits to be cleared from the image, and yours is not:

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

    should be

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g); // note difference?