Java CA-1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Advanced Java Lab 21MSIT2H05L

CA-1

Write a java program that simulates a traffic light. The program lets the user select one of three
lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one
light can be on at a time. No light is on when the program starts.

Solution:

Step-1: Open Netbeans/Eclipse

Step-2: File  New Project(Name: CA1Swing)  classname(Name: CA1Swing)

Step-3: Add below code

package ca1swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class CA1Swing{
JFrame frame = new JFrame("Traffic Lights");
JRadioButton radB1 = new JRadioButton("Red");
JRadioButton radB2 = new JRadioButton("Yellow");
JRadioButton radB3 = new JRadioButton("Green");
JTextField textF1 = new JTextField();
JTextField textF2 = new JTextField();
JTextField textF3 = new JTextField();
ButtonGroup buttonG = new ButtonGroup();
CA1Swing()
{
buttonG.add(radB1);
buttonG.add(radB2);
buttonG.add(radB3);
textF1.setEditable(false);
textF2.setEditable(false);
textF3.setEditable(false);
textF1.setBackground(Color.WHITE);
textF2.setBackground(Color.WHITE);
textF3.setBackground(Color.WHITE);
radB1.addActionListener(new ActionListener() {

MScIT - School of CS & IT Raghavendra R Asst. Prof Page 1


Advanced Java Lab 21MSIT2H05L

public void actionPerformed(ActionEvent e) {


textF1.setBackground(Color.RED);
textF2.setBackground(Color.WHITE);
textF3.setBackground(Color.WHITE);
}
});
radB2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textF1.setBackground(Color.WHITE);
textF2.setBackground(Color.YELLOW);
textF3.setBackground(Color.WHITE);
}
});
radB3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textF1.setBackground(Color.WHITE);
textF2.setBackground(Color.WHITE);
textF3.setBackground(Color.GREEN);
}
});
frame.add(radB1);
frame.add(textF1);
frame.add(radB2);
frame.add(textF2);
frame.add(radB3);
frame.add(textF3);
frame.setLayout(new GridLayout(3,2));
frame.setSize(500,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public static void main(String[] args) {


CA1Swing tl = new CA1Swing();
}
}

Output:

MScIT - School of CS & IT Raghavendra R Asst. Prof Page 2


Advanced Java Lab 21MSIT2H05L

MScIT - School of CS & IT Raghavendra R Asst. Prof Page 3

You might also like