Java IDE中的JButton将单击,但不在.jar文件中

Java IDE中的JButton将单击,但不在.jar文件中,java,swing,jbutton,thread-sleep,Java,Swing,Jbutton,Thread Sleep,在Netbeans IDE中,我编写了一个在JFrame中创建JButton的程序。JButton是可见的,并且可以单击,但是当JButton被单击时,程序有时不会检测到它。当我从Netbeans为您自动编译的.jar文件运行它时,发生这种情况的情况总是。等待单击JButton的代码如下所示: while(!(btn.getModel().isPressed())){ //btn is the JButton here } 当我在IDE中运行Netbeans时,它可以在Netbeans中工作,

在Netbeans IDE中,我编写了一个在JFrame中创建JButton的程序。JButton是可见的,并且可以单击,但是当JButton被单击时,程序有时不会检测到它。当我从Netbeans为您自动编译的.jar文件运行它时,发生这种情况的情况总是。等待单击JButton的代码如下所示:

while(!(btn.getModel().isPressed())){ //btn is the JButton here
}
当我在IDE中运行Netbeans时,它可以在Netbeans中工作,但当程序使用.jar文件运行时,它从不检测何时单击JButton。我尝试的一件事是在循环中添加延迟。起初,我认为循环速度太快,无法检测到一次单击,因此我在两次单击之间添加了1毫秒的延迟:

while(!(btn.getModel().isPressed())){
    try{
        Thread.sleep(1);
    }catch(InterruptedException e){
        '//Exception handling
    }
}

这也适用于IDE,但在.jar文件中仍然不起作用。
btn.getModel().isPressed()是否有问题?如果出现问题,那么除了
btn.getModel().isPressed()
,什么是好的替代方案?

您可能需要尝试使用ActionListener

要将ActionListener添加到按钮,请使用以下命令:
btn.addActionListener(新ActionListener(){})
现在您已经完成了,在ActionListener内部,将以下方法放入:
public void actionPerformed(ActionEvent arg0){}

现在您已经完成了,请将
线程.sleep(1)
插入到
actionPerformed
方法中。

我会尝试,但您能否解释一下为什么它只在我的IDE中单击?这仍然让我很困惑。