日期:2014-05-20  浏览次数:20886 次

线程无法重新启动!
题目是这样的:一个窗口中,在四个位置循环显示四种不同颜色的正方形,当鼠标点击
时,停止循环显示,再次点击,恢复显示。
我写的程序只能点一下让他停了,却不能点一下再次启动!求解!

package t;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
public class bianhuan2 extends JFrame
{
public bianhuan2()
{
super("颜色变换1");
this.setBounds(300,240,400,300);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().add(new panel1());
this.setVisible(true);

}
private class panel1 extends JPanel implements Runnable,MouseListener
{
Color c[]={Color.red,Color.green,Color.black,Color.blue};
Label l1,l2,l3,l4;
boolean f;
Thread b;
panel1()
{
this.setLayout(new GridLayout(2,2));
f=true;
l1=new Label();
l2=new Label();
l3=new Label();
l4=new Label();
add(l1);
add(l2);
add(l3);
add(l4);
l1.addMouseListener(this);
l2.addMouseListener(this);
l3.addMouseListener(this);
l4.addMouseListener(this);
b=new Thread(this);
b.start();
l1.setBackground(c[0]);
l2.setBackground(c[1]);
l3.setBackground(c[2]);
l4.setBackground(c[3]);

}
public void run()
{
while(f)

{

Color t=c[0];
for(int i=0;i<3;i++)
{

c[i]=c[i+1];
}
c[3]=t;

try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
l1.setBackground(c[0]);
l2.setBackground(c[1]);
l3.setBackground(c[2]);
l4.setBackground(c[3]);
}
 
}

@Override
public void mouseClicked(MouseEvent e) {


/*if(f==false)
{
b=new Thread();
b.start();
}
else
b.interrupt();*/
f=!f;
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub

}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub

}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub

}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub

}



}
public static void main(String args[])
{
new bianhuan2();

}
}


------解决方案--------------------
b=new Thread();
b.start();
这个是什么意思 重新new出来的东西肯定不会继续啊,要用原来那个对象啊,线程你让它暂停yield(),再点的时候就继续啊
------解决方案--------------------
public void mouseClicked(MouseEvent e) {

if (f == false) {
f = true;
b = new Thread(this);
b.start();
} else {
f = false;
}


}