Professional Documents
Culture Documents
Traffic Light Code
Traffic Light Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* This is the Traffic Light class
*/
public class TrafficLight extends JFrame implements ActionListener {
/*
* GUI components
*/
private JFrame jframe;
private JPanel jpanel;
private JButton jbtRotate,jbtExit;
private TrafficPanel trafficPanel;
/**
* This constructor initialize the state of the traffic light.
*/
public TrafficLight() {
jframe = new JFrame("Traffic Light");
jpanel = new JPanel();
jbtRotate = new JButton("Rotate");
jbtExit = new JButton("Exit");
}
/**
* Method to add the GUI components to the frame, arrange them,
* and makes the frame visible to the user.
*/
public void launchApp() {
jframe.setSize(200,350);
JOptionPane.showMessageDialog(this,
"Click on the Rotate button to" + "\
nchange the traffic status." ,
"Welcome!", JOptionPane.INFORMATION_MESSAGE);
}
/**
* This the driver program
*/
public static void main(String args[]) {
TrafficLight trafficLight = new TrafficLight();
trafficLight.launchApp();
}
/**
* This method traps the button click events
*/
public void actionPerformed(ActionEvent e) {
// Rotate button is clicked
if (e.getSource() == jbtRotate) {
// Change the color displayed
trafficPanel.changeColor();
}
/**
* The Traffic Panel class
*/
class TrafficPanel extends JPanel {
/**
* This method repaints the light status
*/
public void changeColor() {
lightState++;
if (lightState > 3) {
lightState = 1;
}
repaint();
}
/**
* This method draws the traffic light on the screen
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
switch(lightState) {
case 1:
// RED bulb glows
g.setColor(new Color(255,0,0));
g.fillOval(70,40,50,50);
break;
case 2:
// YELLOW bulb glows
g.setColor(new Color(255,255,0));
g.fillOval(70,100,50,50);
break;
case 3:
// GREEN bulb glows
g.setColor(new Color(0,255,0));
g.fillOval(70,160,50,50);
break;
}
}
} // End of class Traffic Panel