IDE 中的 JButton 会点击,但不会在 .jar 文件中点击

JButton in IDE will click, but not in the .jar file

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

while(!(btn.getModel().isPressed())){ //btn is the JButton here
}

这在 Netbeans 中有效,当我 运行 它在 IDE 中时,但当程序 运行 使用 .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(new ActionListener(){ }); 现在你已经完成了,在 ActionListener 内部,放置这个方法: public void actionPerformed(ActionEvent arg0){ } 现在你已经完成了,将 Thread.sleep(1) 插入到 actionPerformed 方法中。