Last active
February 21, 2023 11:58
-
-
Save B-R-P/d54ba03fefd9b3f243dfd80433cb9525 to your computer and use it in GitHub Desktop.
Traffic Light Simulation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.swing.*; | |
import java.awt.*; | |
import java.awt.event.*; | |
class Light extends JPanel implements ActionListener { | |
private JRadioButton r1,r2,r3; | |
private Color color1,color2,color3,bgcolor; | |
Light() { | |
setBounds(0, 0, 640, 480); | |
r1 = new JRadioButton("Red"); | |
r2 = new JRadioButton("Yellow"); | |
r3 = new JRadioButton("Green"); | |
r1.setSelected(true); | |
bgcolor = getBackground(); | |
color1 = Color.red; | |
color2 = bgcolor; | |
color3 = bgcolor; | |
ButtonGroup gp = new ButtonGroup(); | |
gp.add(r1); | |
gp.add(r2); | |
gp.add(r3); | |
add(r1); | |
add(r2); | |
add(r3); | |
r1.addActionListener(this); | |
r2.addActionListener(this); | |
r3.addActionListener(this); | |
} | |
public void actionPerformed(ActionEvent e) { | |
color1 = bgcolor; | |
color2 = bgcolor; | |
color3 = bgcolor; | |
if(r1.isSelected()) color1 = Color.red; | |
else if(r2.isSelected()) color2 = Color.yellow; | |
else if(r3.isSelected()) color3 = Color.green; | |
repaint(); | |
} | |
public void paintComponent(Graphics g) { | |
super.paintComponent(g); | |
// x y cx cy | |
g.drawOval(50, 50, 50, 50); | |
g.drawOval(50, 110, 50, 50); | |
g.drawOval(50, 170, 50, 50); | |
g.setColor(color1); | |
g.fillOval(50, 50, 50, 50); | |
g.setColor(color2); | |
g.fillOval(50, 110, 50, 50); | |
g.setColor(color3); | |
g.fillOval(50, 170, 50, 50); | |
} | |
} | |
public class traffic { | |
public static void main(String args[]) { | |
JFrame f = new JFrame(); | |
f.setSize(640, 480); | |
f.setLayout(null); | |
f.add(new Light()); | |
f.setVisible(true); | |
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment