我刚刚在我的 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)
是不正确的。
如果没有顶级窗口,有没有办法告诉 Swing 事件调度线程自动退出?
如果不是,如果目标是在所有顶级窗口关闭时退出程序,那么 JDialog/JFrame 在关闭时应该做什么?
您可以使用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();
}
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)