import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class B extends JFrame
{
JButton bnt=new JButton("Start");
B()
{
bnt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
while(true)
{
System.out.println("aa");
try
{
Thread.sleep(2000);
}
catch (Exception a)
{
}
}
}
});
getContentPane().add(bnt);
setSize(400,300);
show();
fun();
}
public void fun()
{
while(true)
{
System.out.println("bb");
try
{
Thread.sleep(2000);
}
catch (Exception a)
{
}
} }
public static void main(String args[])
{
new B();
}
};
为什么开始时有个死循环,还可以执行点击按钮,而点击按钮后的死循环则不可以再点击按钮呢?

解决方案 »

  1.   

    fun()很有问题,因为它在构造器中
      

  2.   

    迷糊不明白你要实现什么功能,个人认为:因为是个死循环,休眠2S再System.out.println();
    所以不能再点,还有是在一个线程下
      

  3.   

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class B extends JFrame
    {
    JButton bnt=new JButton("Start");
    Thread t=new Thread();
    B()
    {
    bnt.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent e)
    {
    while(true)
    {
    System.out.println("aa");
    try
    {
    Thread.sleep(2000);
    }
    catch (Exception a)
    {
    }
    }
    }
    });
    getContentPane().add(bnt);
    setSize(400,300);
    show();
    t.start();
    //fun();
    }
    public void run()
    {
    while(true)
    {
    System.out.println("bb");
    try
    {
    Thread.sleep(2000);
    }
    catch (Exception a)
    {
    }
    } }
    public static void main(String args[])
    {
    new B();
    }
    };