java / swing中closures窗口的正确动作是什么?

我只是在我的CustomUIPanel类中写了这个testing代码:

public static void main(String[] args) { final JDialog dialog = CustomUIPanel.createDialog(null, CustomUIPanel.selectFile()); dialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } 

它工作正常,如果CustomUIPanel.main()是程序的入口点,但它让我想知道:如果另一个类调用CustomUIPanel.main()testing? 然后我对System.exit(0)调用是不正确的。

如果没有顶层窗口,是否有办法告诉Swing事件派发线程自动退出?

如果没有,如果closures所有顶层窗口时程序退出的目标是JDialog / JFrame在closures时执行什么操作是正确的?

您可以使用JDialogsetDefaultCloseOperation()方法,指定DISPOSE_ON_CLOSE

 setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 

另请参阅12.8程序退出 。

附录:结合@ camickr的有用答案,当窗口closures或closuresbutton被按下时,这个例子就会退出。

 import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; /** @see http://stackoverflow.com/questions/5540354 */ public class DialogClose extends JDialog { public DialogClose() { this.setLayout(new GridLayout(0, 1)); this.add(new JLabel("Dialog close test.", JLabel.CENTER)); this.add(new JButton(new AbstractAction("Close") { @Override public void actionPerformed(ActionEvent e) { DialogClose.this.setVisible(false); DialogClose.this.dispatchEvent(new WindowEvent( DialogClose.this, WindowEvent.WINDOW_CLOSING)); } })); } private void display() { this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new DialogClose().display(); } }); } } 

不知道什么时候使用JDialog。

但是在使用JFrame时,应该使用frame.dispose()。 如果该帧是最后一个打开的帧,那么VM将退出。

注意一个对话框没有EXIT_ON_CLOSE选项,因为它通常不应该退出虚拟机。

closures对话框时,你总是可以得到对话框的父框架。 然后你可以派发一个事件到框架来告诉它自己closures。 就像是:

 WindowEvent windowClosing = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING); //Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowClosing); frame.dispatchEvent(windowClosing); 

好,

你可以用一个JFrame来代替。 JDialog应该被用作在JFrame中运行的应用程序的popup窗口,以吸引用户的注意力并暂停主应用程序。 如果JFrameclosures,您可以调用System.exit(0)

对话框有一个getParent()方法,我猜,在你的情况下这里设置为null CustomUIPanel.createDialog(null,

你可以使用它来有条件地退出。

这是我会build议: dialog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

使用

 this.dispose(); 

它应该工作。