请使用以下代码:
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
一次,每个祖先获得一次。 :/
但也许这是预期的行为?
答案 0 :(得分:1)
应在主框架上使用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);
}
}