Question: / / Java Program to Implement Traffic signal / / Using Java Swing Components / / Importing required classesimport java.awt. * ;import java.awt.event. * ;import
Java Program to Implement Traffic signal Using Java Swing Components Importing required classesimport java.awt.;import java.awt.event.;import java.util.;import javax.swing.; Main class Extending JFrame class and Implementing ItemListener interfacepublic class TrafficSignalextends JFrame implements ItemListener Setting the buttons for the layoutJRadioButton jr;JRadioButton jr;JRadioButton jr; Setting the field areaJTextField j new JTextField;ButtonGroup b new ButtonGroup;String msg ; Initially setting the coordinates to int x y z ;public TrafficSignalString msgsupermsg;setLayoutnew FlowLayout; Assigning name to the button declared above with help of JRadioButton classjr new JRadioButtonRed;jr new JRadioButtonYellow;jr new JRadioButtonGreen;jraddItemListenerthis;jraddItemListenerthis;jraddItemListenerthis;addjr;addjr;addjr;baddjr;baddjr;baddjr;addj; Method To add a windowaddWindowListenernew WindowAdapterpublic void windowClosingWindowEvent e It haults here itselfSystem.exit;; Method To change colors of traffic signalpublic void itemStateChangedItemEvent ie If it is redif iegetSource jrif iegetStateChange Then display message Stopmsg "Stop!";x ; Repainting the box with original one Practically blackrepaint;else msg ; If state is Orange or technically jrif iegetSource jrif iegetStateChange Then display message Get ready in waiting statemsg "Get Ready to go;y ; Again repainting the buttonrepaint;else msg ; If state is Greenif iegetSource jrif iegetStateChange Then display message Gomsg Go;z ;repaint;else msg ;jsetTextmsg; Method handling the paint graphics and dimensions of the buttons via setting coordinatespublic void paintGraphics ggdrawRect;gdrawOval;gdrawOval;gdrawOval; Case: Redif x gsetColorColorRED;gfillOval;gsetColorColorWHITE;gfillOval;gsetColorColorWHITE;gfillOval;x ; Case: Orangeif y gsetColorColorWHITE;gfillOval;gsetColorColorYELLOW;gfillOval;gsetColorColorWHITE;gfillOval;y ; Case: Greenif z gsetColorColorWHITE;gfillOval;gsetColorColorWHITE;gfillOval;gsetColorColorGREEN;gfillOval;z ; Method Main driver methodpublic static void mainString args Creating object of Jframe class inside main methodJFrame jf new TrafficSignalTraffic Light"; Setting size and making traffic signal operational using setVisible methodjf.setSize;jfsetVisibletrue;
Project : Add more lights to the traffic signal. Explain what you did and how you did it
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
