这是我的代码!
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();
}
}
这里的主要课程:
public class StartProj {
public static void main(String[] args) {
DataModels dm = new DataModels();
Simulation sm = new Simulation(dm);
sm.create();
}
}
我尝试为 Frame 中的矩形设置动画,但是它重复了多个矩形。怎么了?帮我?我还有一些课,但它们不是必需的。非常感谢你