在java/swing中关闭窗口时采取的正确行动是什么?

Jas*_*n S 14 java swing dialog

我刚在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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

它是正确的,如果CustomUIPanel.main()是程序的入口点,但它让我想知道:如果另一个类要求CustomUIPanel.main()测试怎么办?然后我的电话System.exit(0)是不正确的.

如果没有顶级窗口,有没有办法告诉Swing事件调度线程自动退出?

如果不是,如果目标是让所有顶级窗口关闭时程序退出,那么JDialog/JFrame在关闭时做什么是正确的?

tra*_*god 15

您可以使用setDefaultCloseOperation()的方法JDialog,规定DISPOSE_ON_CLOSE:

setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
Run Code Online (Sandbox Code Playgroud)

另请参见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();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 啊哈!你是对的,这里的关键文档是"注意:当Java虚拟机(VM)中的最后一个可显示窗口被丢弃时,VM可能会终止." (http://download.oracle.com/javase/6/docs/api/javax/swing/JDialog.html#setDefaultCloseOperation%28int%29)我从未意识到这是处置窗口的有用副作用. (3认同)