import javax.swing.JFrame;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.JComponent;
public class CarMover {
public static void main(String[] args) {
Car someCar = new Car(0, 0, Color.RED);
Car someCar2 = new Car(100, 0, Color.BLUE);
JFrame windowFrame = new JFrame();
windowFrame.getContentPane().setLayout(new GridLayout(2, 2));
final int WINDOWFRAMEWIDTH = 300;
final int WINDOWFRAMEHEIGHT = 400;
final int FRAMEDELAY = 50; // milliseconds
windowFrame.setSize(WINDOWFRAMEWIDTH, WINDOWFRAMEHEIGHT);
windowFrame.setTitle("Car Animation");
windowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CarComponent component = new CarComponent(someCar);
CarComponent component2 = new CarComponent(someCar2);
windowFrame.add(component);
windowFrame.add(component2);
windowFrame.setVisible(true);
Timer carTimer = new Timer(FRAMEDELAY, new TimerListener(someCar, component));
carTimer.start();
Timer carTimer2 = new Timer(FRAMEDELAY, new TimerListener(someCar2, component2));
carTimer2.start();
}
static class TimerListener implements ActionListener {
Car car;
JComponent jc;
public TimerListener(Car c, JComponent j)
{
car = c;
jc = j;
}
public void actionPerformed(ActionEvent event) {
if (car.getX() > jc.getWidth() || car.getY() > jc.getHeight()) {
car.move(0, 0);
} else {
car.translate(0, 1);
}
jc.repaint();
}
}
}
Do more with
Premium Content
You need an Expert Office subscription to comment.Start Free Trial