Search code examples
javaswingpaintcomponent

repeat rectangle instead of moving animation


This is my code!

package softwarea1;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Leo
 */
//534
public class Simulation extends JPanel implements ActionListener
{
    DataModels dm;
    Timer tm = new Timer(20, this);
    private int velX = 2;
    private int a = 0; 

    public void create()
    {

        Simulation sm = new Simulation(dm);
        JFrame simulation = new JFrame();
        simulation.setTitle("Traffic light and Car park Siumulation");
        simulation.setSize(600,600);
        simulation.setResizable(false);
        simulation.setVisible(true);
        simulation.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        simulation.add(sm);
    }
    public void paintComponent(Graphics g)
    {



        // Moving Rectangle
        g.setColor(Color.RED);
        g.fillRect(a ,300, 1 ,30);
        tm.start();
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        a += velX;
        repaint();
    }


}

Main Class here:

 public class StartProj {
        public static void main(String[] args) {
            DataModels dm = new DataModels();
            Simulation sm = new Simulation(dm);
            sm.create();

        }
    }

I try animate the rectangle in the Frame however it repeats multiple rectangle. What wrong? Help me? I have some more class but they are not necessary. Thank you very much


Solution

  • Your paintComponent(...) method needs to call the super's method on the first line:

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g); // **** add this
        // Moving Rectangle
        g.setColor(Color.RED);
        g.fillRect(a ,300, 1 ,30);
        // tm.start(); // **** get rid of this.
    }
    

    This is important because the super method repaints the component's background, and this is needed to erase the old rectangles.

    Also, you have program logic inside of this method, you start a Swing Timer from inside, something that should never be done. Instead find a better more controllable place to start your Timer.