展开全部
这样可以么import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.Timer;
public class MainFrame extends JFrame implements ActionListener{
private ButtonGroup bg = new ButtonGroup();
private ProccessControl lightPanel = new ProccessControl(0);
private JRadioButtonmode_1 = new JRadioButton("MODE 1"),
e68a84e8a2ad62616964757a686964616f31333337383937mode_2 = new JRadioButton("MODE 2");
public MainFrame() {
super("Signal Light");
this.setSize(new Dimension(300, 300));
this.setLayout(null);
lightPanel.setBounds(50, 10, 80, 240);
mode_1.setBounds(150, 75, 80, 50);
mode_2.setBounds(150, 125, 80, 50);
mode_1.addActionListener(this);
mode_2.addActionListener(this);
bg.add(mode_1);
bg.add(mode_2);
mode_1.setSelected(true);
this.add(lightPanel);
this.add(mode_1);
this.add(mode_2);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(mode_1)) {
lightPanel.setControlMode(0);
} else {
lightPanel.setControlMode(1);
}
}
public static void main(String[] args) {
new MainFrame();
}
}
class ProccessControl extends JPanel implements ActionListener{
private SignalLight[] light = new SignalLight[3];
private int controlMode;
private Timer timer = new Timer(1000, this);
private final Color[][] color = { {Color.GREEN, Color.YELLOW, Color.RED}, {Color.RED, Color.YELLOW, Color.GREEN} };
private int currentLight;
public ProccessControl(int controlMode) {
this.setControlMode(controlMode);
this.setOpaque(true);
this.setLayout(new GridLayout(3, 1));
for(int i = 0; i
light[i] = new SignalLight();
light[i].setOff();
this.add(light[i]);
}
currentLight = 0;
light[currentLight].setOn(color[controlMode][currentLight]);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
currentLight = (currentLight + 1) % 3;
for(int i = 0; i
light[i].setOff();
light[currentLight].setOn(color[controlMode][currentLight]);
}
public int getControlMode() {
return controlMode;
}
public void setControlMode(int controlMode) {
this.controlMode = controlMode;
}
class SignalLight extends JLabel {
public SignalLight() {
this.setOpaque(true);
this.setPreferredSize(new Dimension(80, 80));
this.setFont(new Font("MS 明朝", Font.BOLD, 60));
this.setText("●");
}
public void setOn(Color color) {
this.setForeground(color);
}
public void setOff() {
this.setForeground(this.getBackground());
}
}
}