Answer to Question #299879 in Java | JSP | JSF for soni

Question #299879

: Write a java program that simulates a traffic light. The program lets the user select one of three lights: red, yellow, or green with radio buttons. On entering the choice, an appropriate message with “stop” or “ready” or “go” should appear in the console .Initially there is no message shown.


1
Expert's answer
2022-02-19T16:56:35-0500


import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


import javax.swing.*;


class MainJFrame extends JFrame {
	JFrame actualWindow;
	JPanel messageContainer, lightsContainer;


	ButtonGroup btnGroup;
	JRadioButton rbRed, rbYellow, rbGreen;


	public MainJFrame() {


		actualWindow = new JFrame("Traffic Lights");
		messageContainer = new JPanel();
		lightsContainer = new JPanel();
		btnGroup = new ButtonGroup();
		rbRed = new JRadioButton("Red");
		rbYellow = new JRadioButton("Yellow");
		rbGreen = new JRadioButton("Green");


		actualWindow.setLayout(new GridLayout(2, 1));


		btnGroup.add(rbRed);
		btnGroup.add(rbYellow);
		btnGroup.add(rbGreen);


		lightsContainer.add(rbRed);
		lightsContainer.add(rbYellow);
		lightsContainer.add(rbGreen);


		rbRed.addActionListener(new ActionListener() {


			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("stop");


			}
		});


		rbYellow.addActionListener(new ActionListener() {


			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("ready");


			}
		});


		rbGreen.addActionListener(new ActionListener() {


			@Override
			public void actionPerformed(ActionEvent e) {
				System.out.println("go");


			}
		});


		actualWindow.add(messageContainer);
		actualWindow.add(lightsContainer);


		actualWindow.setSize(300, 200);
		actualWindow.setVisible(true);
	}


}


public class App {


	public static void main(String[] args) {
		new MainJFrame();
	}


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS