[求助]关于线程的使用
写个JAVA程序,用线程模拟一个竖状的交通灯,红黄绿 3个灯从上到下依次排列,每秒从上到下一个灯亮,其他两个灭,3个灯依次循环
import java.awt.Color;
import java.awt.Graphics;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
public class PowerTest extends JPanel implements Runnable{
private ColorLabel[] colorLabel;
private Thread t;
private int i=0;
private JPanel jpanel;
public PowerTest(){
init();
}
private void init(){
this.setLayout(new BorderLayout());
colorLabel=new ColorLabel[3];
jpanel=new JPanel();
jpanel.setLayout(new GridLayout(3,1));
colorLabel[0]=new ColorLabel();
colorLabel[0].setSize(30,30);
colorLabel[0].setBackground(new Color(170,0,0));
colorLabel[1]=new ColorLabel();
colorLabel[1].setSize(30,30);
colorLabel[1].setBackground(new Color(255,170,0));
colorLabel[2]=new ColorLabel();
colorLabel[2].setSize(30,30);
colorLabel[2].setBackground(new Color(0,170,0));
jpanel.add(colorLabel[0]);
jpanel.add(colorLabel[1]);
jpanel.add(colorLabel[2]);
this.add(jpanel,BorderLayout.CENTER);
t=new Thread(this,"power");
t.start();
}
public void run(){
while(true){
try{
if(i==0){
colorLabel[0].setBackground(new Color(250,0,0));
colorLabel[1].setBackground(new Color(255,170,0));
colorLabel[2].setBackground(new Color(0,170,0));
colorLabel[0].repaint();
colorLabel[1].repaint();
colorLabel[2].repaint();
i=1;
}else if(i==1){
colorLabel[0].setBackground(new Color(170,0,0));
colorLabel[1].setBackground(new Color(255,255,0));
colorLabel[2].setBackground(new Color(0,170,0));
colorLabel[0].repaint();
colorLabel[1].repaint();
colorLabel[2].repaint();
i=2;
}else if(i==2){
colorLabel[0].setBackground(new Color(170,0,0));
colorLabel[1].setBackground(new Color(255,170,0));
colorLabel[2].setBackground(new Color(0,255,0));
colorLabel[0].repaint();
colorLabel[1].repaint();
colorLabel[2].repaint();
i=0;
}
Thread.sleep(1000);
}catch(Exception e){
System.out.println(e.toString());
}
}
}
public static void main(String[] args){
JFrame jframe=new JFrame("红绿灯");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.getContentPane().add(new PowerTest());
jframe.setSize(200,500);
jframe.setVisible(true);
}
}
class ColorLabel extends JLabel{
public void paintComponent(Graphics g){
g.setColor(this.getBackground());
g.fillOval(0,0,this.getWidth(),this.getHeight());
super.paintComponent(g);
}
public void paintBorder(Graphics g){
g.setColor(Color.black);
g.drawOval(0,0,this.getSize().width-1,this.getSize().height-1);
}
}