Write an application that draws a traffic light and uses a push button to change
ID: 3671368 • Letter: W
Question
Write an application that draws a traffic light and uses a push button to change the state of the light. Derive the drawing surface from the JPanel class and use another panel to organize the drawing surface and the button.
After completing this assignment you should have two files PP4_17.java(the file with the main method in it) and Trafficlight.java
You should have three colors on the light: red/yellow/green
The next color chosen should follow the typical pattern for a traffic light- green/yellow/red and then back to green again.
Explanation / Answer
import javax.swing.*; import java.awt.*; import java.awt.event.*; class Lights extends JPanel { public static int RED = 1; public static int YELLOW = 2; public static int GREEN = 3; private final int top, left, lightSize; private final Color unlitColor = Color.lightGray; private int state; public Lights(int left, int top, int lightSize) { // your code here } private void drawLight(Graphics g, int x, int y, int lightType, Color litColor) { // check state for color // g.setColor( g.fillOval(left + x, top + y, lightSize, lightSize); } public void paintComponent(Graphics g) { drawLight(g, 20, 20, RED, Color.RED); drawLight(g, 20, 100, YELLOW, Color.YELLOW); drawLight(g, 20, 180, GREEN, Color.GREEN); } public void setState(int value) { /* your code here */ } public int getState() { /* your code here */ } } class Buttons extends JPanel { private final JButton bChange; public Buttons(ActionListener listener) { this.bChange = new JButton("Change to XXXX"); bChange.addActionListener(listener); add(bChange); } // this will set the text for the button public void setState(int value) { /* your code here */ } } public class TrafficPanel extends JPanel implements ActionListener { private final Lights lights; private final Buttons buttons; public TrafficPanel() { this.lights = new Lights(50, 50, 60); this.buttons = new Buttons(this); buttons.setState(lights.getState()); add(lights); add(buttons); setPreferredSize(new Dimension(200,400)); setBackground(Color.black); } public void actionPerformed(ActionEvent e) { System.out.println("Action Called"); int nextState = getNextState(); lights.setState(nextState); buttons.setState(nextState); } private int getNextState() { /* your code here */ } public static void main(String[] args) { JFrame frm = new JFrame("Traffic Light"); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.getContentPane().add(new TrafficPanel()); frm.pack(); frm.setVisible(true); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.