我刚刚在我的 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 Program Exit .
附录:结合@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();
}
});
}
}
关于java - 在 java/swing 中关闭窗口时正确的操作是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5540354/