简体   繁体   English

有没有办法使用同一对象多次弹出对话框?

[英]Is there a way to bring up a dialog multiple times using the same object?

Right now, to bring up a dialog I create a new JDialog object, then call dispose to exit the dialog. 现在,要弹出对话框,我创建了一个新的JDialog对象,然后调用dispose退出对话框。

Is there a way I can create a dialog, and call up the same dialog later, using the same object? 有没有办法我可以创建一个对话框,并稍后使用同一对象调用同一对话框?

The reason I want to do this is so that the values in the text fields will keep their values. 我想这样做的原因是为了使文本字段中的值保持其值。

JDialog d = new JDialog();
d.setVisible(false);

You can also use this.setVisible(false) inside the dialog, so it doesn't get destroyed and is usable from the parent class. 您还可以在对话框中使用this.setVisible(false) ,因此它不会被破坏并且可以在父类中使用。 Also if it has input fields they don't get cleared out. 另外,如果它具有输入字段,则不会清除它们。 It's invisible in the windows10 taskbar, don't know about linux. 它在Windows10任务栏中不可见,不了解linux。

For dialogs that will be shown/hidden often, I use the singleton pattern. 对于经常显示/隐藏的对话框,我使用单例模式。 As long as you never need more than one of them, like a "Settings" dialog for example. 只要您不需要多个选项,例如“设置”对话框。 Make a class that extends JDialog using a singleton pattern . 创建一个使用单例模式扩展JDialog的类。

public class SettingsDialog extends JDialog {

    private static SettingsDialog instance = null;

    public static SettingsDialog getInstance() {
        if (instance == null) {
            instance = new SettingsDialog();
        }
        return instance;
    }

    private SettingsDialog() {
        super();
    }
}

Then when you want to show your dialog (from a button or menu item action listener) as others have mentioned use the setVisible method. 然后,当您想要显示对话框(通过按钮或菜单项操作侦听器)时,如其他人所述,请使用setVisible方法。

SettingsDialog.getInstance().setVisible(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM