import java.awt.*;
import java.awt.event.*;
public class Draw1
{
public static void main(String[] args)
{
DrawMachine dm=new DrawMachine();
}
}
class DrawMachine extends Frame implements Runnable,ActionListener
{
Button btn1,btn2;
TextField tf;
Thread trd1;
boolean Flag;
public DrawMachine()
{
super("抽奖机");
setVisible(true);
setSize(300,200);
setBackground(Color.cyan);
setLayout(null);
btn1=new Button("开始");
btn2=new Button("停止");
tf=new TextField(100);
add(btn1);
add(btn2);
add(tf);
btn1.setBounds(90,130,50,30);
btn2.setBounds(150,130,50,30);
tf.setBounds(60,80,170,30);
trd1=new Thread(this);
btn1.addActionListener(this);
btn2.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btn1)
{
Flag=true;
  trd1.start();
btn1.setEnabled(false);
}
if(e.getSource()==btn2)
{
setFlag();
btn1.setEnabled(true);
}
}
public void run()
{
while(Flag)
{
for(int i=1;i<11;i++)
{
tf.setText(""+i);
if(Flag==false)
{
break;
}
}
}
}
public void setFlag()
{
Flag=false;
}
}
//第一次两个按钮都可以使用,第二次点击开始按钮就出错什么原因?谢谢

解决方案 »

  1.   

    线程停止后自动消亡.这就是为什么要在线程加上一个死循环,否则他一执出去,线程就没了。所以每次点“开始”按扭时,再建一个新的线程就可以了。import java.awt.*;
    import java.awt.event.*;public class Draw1 {
    public static void main(String[] args) {
    DrawMachine dm = new DrawMachine();
    }
    }class DrawMachine extends Frame implements Runnable, ActionListener {
    Button btn1, btn2;
    TextField tf;
    Thread trd1;
    boolean Flag; public DrawMachine() {
    super("抽奖机");
    setVisible(true);
    setSize(300, 200);
    setBackground(Color.cyan);
    setLayout(null);
    btn1 = new Button("开始");
    btn2 = new Button("停止");
    tf = new TextField(100);
    add(btn1);
    add(btn2);
    add(tf);
    btn1.setBounds(90, 130, 50, 30);
    btn2.setBounds(150, 130, 50, 30);
    tf.setBounds(60, 80, 170, 30);

    btn1.addActionListener(this);
    btn2.addActionListener(this);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    }
    });
    } public void actionPerformed(ActionEvent e) {
    if (e.getSource() == btn1) {
    trd1 = new Thread(this);
    Flag = true;
    trd1.start();
    btn1.setEnabled(false);
    }
    if (e.getSource() == btn2) {
    setFlag();
    btn1.setEnabled(true);
    }
    } public void run() {
    while (Flag) {
    for (int i = 1; i < 11; i++) {
    tf.setText("" + i);
    if (Flag == false) {
    break;
    }
    }
    }
    } public void setFlag() {
    Flag = false;
    }
    }