我正在尝试使用线程构建一个红绿灯信号量,但我无法正确。信号量应显示红色,黄色,绿色,颜色之间有间断。任何帮助深表感谢。 谢谢。 这是我的代码......
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StopTheLights extends JFrame implements ActionListener {
JButton start;
JButton stop;
JPanel panel;
Boolean flag;
public StopTheLights(String title) {
Container c = getContentPane();
start = new JButton("Start");
stop = new JButton("Stop");
start.addActionListener(this);
stop.addActionListener(this);
panel= new JPanel();
panel.add(start);
panel.add(stop);
c.add(panel, BorderLayout.SOUTH);
setSize(300, 450);
setVisible(true);
setLocation(200,200);
}
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.black);
g.drawOval(50,50,100,100);
g.drawOval(50,155,100,100);
g.drawOval(50,260,100,100);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == start){
flag = true;
new ThreadExtend(this).start();
}else{
flag = false;
}
}
public class ThreadExtend extends Thread {
Graphics g;
JFrame frame;
public ThreadExtend(JFrame frame){
this.frame = frame;
g = frame.getGraphics();
}
public void run(){
while(flag) {
try{
paintRed(g);
if(!flag) {
break;
}
Thread.sleep(1000);
paintAmber(g);
if(!flag) {
break;
}
Thread.sleep(1000);
paintGreen(g);
if(!flag){
break;
}
}catch(InterruptedException e) {
}
}
}
}
public void paintRed(Graphics g){
g.setColor(new Color(255,0,0));
g.fillOval(52, 52, 96, 96);
g.fillOval(52, 52, 96, 96);
g.fillOval(52, 262, 96, 96);
}
public void paintAmber(Graphics g){
g.setColor(new Color(250,170,0));
g.fillOval(52, 157, 96, 96);
g.fillOval(52, 52, 96, 96);
g.fillOval(52, 262, 96, 96);
}
public void paintGreen(Graphics g){
g.setColor(new Color(0,250,0));
g.fillOval(52, 262, 96, 96);
g.fillOval(52, 52, 96, 96);
g.fillOval(52, 157, 96, 96);
}
public static void main(String[] args) {
new StopTheLights();
}
}
答案 0 :(得分:1)
这里有几个问题。
我在你的代码中做了一些修复,现在它可以工作了:
test.mp4