我正在构建一个简单的对话框,可以通过按下按钮或Esc
按钮将其关闭。我在关闭对话框之前使用 CountDownLatch 等待,并.countDown()
从各种侦听器中调用。
我遇到了以下问题 - 在窗口调用上按“X”.countDown()
会导致对话框关闭,而按按钮会导致调用相同的代码,但线程不会恢复执行。可能是什么问题呢?
可编译/可运行示例:
import java.util.concurrent.CountDownLatch;
import javax.swing.JFrame;
public class StrangeDialog extends javax.swing.JDialog {
final CountDownLatch latch = new CountDownLatch(1);
public StrangeDialog(JFrame parent) {
super(parent, true); // removing this line fixes things
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
System.out.println(latch);
latch.countDown();
}
});
setFocusable(true);
addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent e) {
System.out.println(latch);
latch.countDown();
}
});
setSize(100,100);
setVisible(true);
}
public static void main(String[] args) {
StrangeDialog dialog = new StrangeDialog(null);
try {
dialog.latch.await();
} catch (InterruptedException ex) {
}
dialog.setVisible(false);
System.out.println("Released");
}
}