交通信号灯

时间:2024-04-10 07:29:34

编写程序,模拟交通信号灯。程序让用户从红、黄、绿三色灯中选择一种。当选择一个单选按钮后,相应的灯被打开,并且一次只能亮一种灯。如下图所示:


交通信号灯
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Test7 extends JFrame {
private ButtonGroup group = new ButtonGroup();
private Light light = new Light();
JRadioButton jr1 = new JRadioButton("Red");
JRadioButton jr2 = new JRadioButton("Yellow");
JRadioButton jr3 = new JRadioButton("Green");
public static void main(String[] args) {
// TODO 自动生成的方法存根
Test7 frame = new Test7();
frame.setSize(250, 170);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public Test7(){
JPanel p1 = new JPanel();
p1.add(light);
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(jr1);
p2.add(jr2);
p2.add(jr3);
group.add(jr1);
group.add(jr2);
group.add(jr3);
jr1.addActionListener(new MyActionEventListener());
jr2.addActionListener(new MyActionEventListener());
jr3.addActionListener(new MyActionEventListener());
setLayout(new BorderLayout());
add(p1,BorderLayout.CENTER);
add(p2,BorderLayout.SOUTH);
}

class MyActionEventListener  implements ActionListener{
public void actionPerformed(ActionEvent e){
Object obj = e.getSource();
if(obj == jr1){
light.turnOnRed();
}
if(obj == jr2){
light.turnOnYellow();
}
if(obj == jr3){
light.turnOnGreen();
}
}
}

class Light extends JPanel{
private boolean red;
private boolean yellow;
private boolean green;
public Light(){

}
public void turnOnRed(){
red = true; yellow = false;  green = false;
repaint();
}
public void turnOnYellow(){
red = false; yellow = true; green = false;
repaint();
}
public void turnOnGreen(){
red = false; yellow = false; green = true;
repaint();
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawRect(5, 5, 30, 80);
g.drawOval(10, 10, 20, 20);
g.drawOval(10, 35, 20, 20);
g.drawOval(10, 60, 20, 20);
if(red){
g.setColor(Color.RED);
g.fillOval(10, 10, 20, 20);
}
else if(yellow){
g.setColor(Color.YELLOW);
g.fillOval(10, 35, 20, 20);
}else if(green){
g.setColor(Color.GREEN);
g.fillOval(10, 60, 20, 20);
}
}
public Dimension getPreferredSize(){
return new Dimension(40,90);
}
}
}