Traffic Light Simulation

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

public class TrafficLightSimulator extends JFrame implements ActionListener {

    private JRadioButton redButton;
    private JRadioButton yellowButton;
    private JRadioButton greenButton;
    private JPanel lightPanel;

    public TrafficLightSimulator() {
        // Create radio buttons
        redButton = new JRadioButton("Red");
        yellowButton = new JRadioButton("Yellow");
        greenButton = new JRadioButton("Green");

        // Group the radio buttons
        ButtonGroup group = new ButtonGroup();
        group.add(redButton);
        group.add(yellowButton);
        group.add(greenButton);

        // Add action listeners
        redButton.addActionListener(this);
        yellowButton.addActionListener(this);
        greenButton.addActionListener(this);

        // Create a panel for the radio buttons
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        buttonPanel.add(redButton);
        buttonPanel.add(yellowButton);
        buttonPanel.add(greenButton);

        // Create a panel for the lights
        lightPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                drawLights(g);
            }
        };
        lightPanel.setPreferredSize(new Dimension(100, 300));

        // Set up the frame
        setTitle("Traffic Light Simulator");
        setLayout(new BorderLayout());
        add(buttonPanel, BorderLayout.SOUTH);
        add(lightPanel, BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    private void drawLights(Graphics g) {
        // Draw the traffic light outline
        g.setColor(Color.BLACK);
        g.fillRect(30, 30, 40, 200);

        // Draw the red light
        g.setColor(redButton.isSelected() ? Color.RED : Color.GRAY);
        g.fillOval(40, 40, 20, 20);

        // Draw the yellow light
        g.setColor(yellowButton.isSelected() ? Color.YELLOW : Color.GRAY);
        g.fillOval(40, 100, 20, 20);

        // Draw the green light
        g.setColor(greenButton.isSelected() ? Color.GREEN : Color.GRAY);
        g.fillOval(40, 160, 20, 20);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // Repaint the light panel when a button is pressed
        lightPanel.repaint();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TrafficLightSimulator::new);
    }
}

Comments

Popular posts from this blog

KTU OOP LAB JAVA CSL 203 BTech CS S3 - Dr Binu V P

Syllabus and Practice Questions KTU OOPS Lab Java CSL 203

String Problems