java - 在 java/swing 中关闭窗口时正确的操作是什么?

标签 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);
        }
    });
}

如果 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/

相关文章:

java - 高级应用程序中的 JButton 如何工作?

Java Swing - 创建类似标签的动态宽度按钮

jquery - 加载 div 后,jquery ui 对话框不会再次打开

java - 如何在android studio中修复(资源@drawable/abc_vector_test在androix.appcompat :appcompat)中标记为私有(private)

java - 如何获取文件的所有不同大小的系统图标

python - 将 python 输出提供给 whiptail

Android:使 Dialog 周围的一切都比默认更暗

java - 线程中的异常 "main"org.hibernate.exception.ConstraintViolationException : could not execute statement

java - Intellij IDEA。隐藏 .iml 文件

java - 如何使用 AXis 1.4 创建 Java 客户端以使用 wsHttpBinding 使用 WCF 服务