采用以下代码:
import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class WeirdDialogShitTest implements Runnable {
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new WeirdDialogShitTest());
}
@Override
public void run() {
frame = new JFrame("Test");
frame.add(new JButton(new AbstractAction("Show Dialog") {
@Override
public void actionPerformed(ActionEvent event) {
showDialog();
}
}));
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
private void showDialog() {
JDialog dialog = new JDialog(frame, "Dialog", Dialog.ModalityType.DOCUMENT_MODAL);
dialog.add(new JLabel("Content here"));
dialog.pack();
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent event) {
JOptionPane.showMessageDialog(frame, "windowClosed fired");
}
});
dialog.setVisible(true);
}
}
我希望在对话框关闭时调用一次 windowClosed
。
实际发生的是它被调用两次 - 一次是在对话框关闭时,一次是在包含框架关闭时。
当我追踪它以查看发生了什么时,这是我发现的:
- 当在父级上调用
dispose()
时,它也会释放所有子级。很公平。 - 尽管不再存在,但所有子对话仍保留在子列表中。这对我来说似乎很狡猾。 (他们曾经被移除过吗?)
dispose()
无条件地触发windowClosed
无论窗口是否已经被释放。这对我来说也很狡猾。
最终结果是为对话框本身获取一次 windowClosed
,为每个祖先获取一次。 :/
但也许这是预期的行为?
最佳答案
应在主框架上使用 frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
。这将解决您的问题。尝试:
public class WeirdDialogShitTest implements Runnable {
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new WeirdDialogShitTest());
}
@Override
public void run() {
frame = new JFrame("Test");
frame.add(new JButton(new AbstractAction("Show Dialog") {
@Override
public void actionPerformed(ActionEvent event) {
showDialog();
}
}));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//Use EXIT_ON_CLOSE here.
}
private void showDialog() {
JDialog dialog = new JDialog(frame, "Dialog", Dialog.ModalityType.DOCUMENT_MODAL);
dialog.add(new JLabel("Content here"));
dialog.pack();
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent event) {
JOptionPane.showMessageDialog(frame, "windowClosed fired");
}
});
dialog.setVisible(true);
}
}
关于java - windowClosed 触发不止一次。这是错误还是功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20040410/