我刚刚在CustomUIPanel类中编写了以下测试代码:
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()进行测试,该怎么办?那我打给我System.exit(0)是不正确的。
CustomUIPanel.main()
System.exit(0)
如果没有顶层窗口,是否有办法告诉Swing事件分配线程自动退出?
如果不是,如果目标是在所有顶级窗口都关闭时退出程序,那么JDialog / JFrame在关闭时应该做什么呢?
您可以使用的setDefaultCloseOperation()方法JDialog,指定DISPOSE_ON_CLOSE:
setDefaultCloseOperation()
JDialog
DISPOSE_ON_CLOSE
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
另请参见12.8程序退出。
附录:包含@camickr的有用答案,当关闭窗口或按下关闭按钮时,此示例退出。
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(); } }); } }