I am trying to create a traffic light using a Java GUI, where it displays only one circle and it changes colours from red, to yellow, to green. There should be a timer and only
Here is one approach. The lights stay on for 3 seconds. To change their duration the code must be modified accordingly. This would be done inside the timer.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class TrafficLight extends JPanel {
JFrame frame = new JFrame();
int colorIdx = 0;
Color[] colors = { Color.green, Color.yellow, Color.red };
public static void main(String[] args) {
// Ensure the program is started on the Event Dispatch Thread
SwingUtilities.invokeLater(() -> new TrafficLight().start());
}
public void start() {
// set up
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set the preferred size. Okay in this instance but best
// practice dictates to override getPreferredSize()
setPreferredSize(new Dimension(500, 500));
frame.add(this);
frame.pack();
// center on screen
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer t = new Timer(3000, ae -> {
colorIdx = colorIdx >= 2 ? 0 : colorIdx + 1;
repaint();
});
t.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(colors[colorIdx]);
g.fillOval(150, 150, 200, 200);
}
}