java 如何从 jframe 打开 jdialog

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30381351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:01:28  来源:igfitidea点击:

How to open a jdialog from a jframe

javaswingnetbeans

提问by

JFrame button to open the jdialog:

JFrame 按钮打开 jdialog:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:

JDialog method that opens the dialog:

打开对话框的 JDialog 方法:

        public void run() {
            AddClient dialog = new AddClient(new javax.swing.JFrame(), true);
            dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                @Override
                public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                }
            });
            dialog.setVisible(true);

My JDialog class is named AddClient, my JFrame class is named MainWindow. The package these are in is named my.javaapp

我的 JDialog 类名为 AddClient,我的 JFrame 类名为 MainWindow。这些所在的包被命名为 my.javaapp

How would i go onto doing this? I'm pretty new to java, was using python up until this point and dove head in into java swing gui builder with netbeans, i'm planning on watching tutorials and reading through the java documentation to learn more about java, but i would like to start by being able to open this jdialog.

我将如何继续这样做?我对 Java 还很陌生,到目前为止一直在使用 python 并使用 netbeans 深入研究 java swing gui builder,我计划观看教程并通读 java 文档以了解有关 java 的更多信息,但我想首先能够打开这个 jdialog。

Before asking this question i searched a lot, and i read other questions that had been asked to solve more or less this same problem, i still couldn't solve mine though so i'm asking.

在问这个问题之前,我搜索了很多,我阅读了其他问题,这些问题或多或少地解决了同样的问题,但我仍然无法解决我的问题,所以我在问。

Solution:

解决方案:

Delete the main function from the class the gui you want to pop up is on e.g

从你想要弹出的 gui 所在的类中删除 main 函数,例如

public static void main(String args[]) {

    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewJDialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJDialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJDialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJDialog1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            NewJDialog1 dialog = new NewJDialog1(new javax.swing.JFrame(), true);
            dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                @Override
                public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                }
            });
            dialog.setVisible(true);
        }
    });
}

Before deleting though, copy this line:

在删除之前,复制这一行:

NewJDialog1 dialog = new NewJDialog1(new javax.swing.JFrame(), true);

Right click the button you want to pop this window up after pressing, events > action > action performed. Paste it there like this:

按下后右键单击要弹出此窗口的按钮,事件> 操作> 执行的操作。像这样粘贴它:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

NewJDialog1 dialog = new NewJDialog1(new javax.swing.JFrame(), true); 

dialog.setVisible(true);

}

Remember to add the last line, that's what shows up the dialog.

记住添加最后一行,这就是显示对话框的内容。

回答by mr mcwolf

The constructor on JDialog accept parent object. But you use new JFrame object. This is error (logical error).

JDialog 上的构造函数接受父对象。但是您使用新的 JFrame 对象。这是错误(逻辑错误)。

AddClient dialog = new AddClient(MainWindow.this);

If you want modal dialog, call

如果你想要模态对话框,请调用

dialog.setModal(true);

And set default close operation.

并设置默认关闭操作。

dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

Use of thread is unnecessary.

不需要使用线。

Ps: sorry for bad English

Ps:抱歉英语不好

Edit:Here is simple example with exit code in dialog

编辑:这是对话框中退出代码的简单示例

public class AddClient extends JDialog {
    public static final int ID_OK = 1;
    public static final int ID_CANCEL = 0;

    private int exitCode = ID_CANCEL;

    public AddClient(Frame owner) {
        super(owner);
        createGUI();
    }

    public AddClient(Dialog owner) {
        super(owner);
        createGUI();
    }

    private void createGUI() {
        setPreferredSize(new Dimension(600, 400));
        setTitle(getClass().getSimpleName());

        pack();
        setLocationRelativeTo(getParent());
    }

    @Override
    public void dispose() {
        super.dispose();
    }

    public int doModal() {
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setModal(true);
        setVisible(true);

        return exitCode;
    }
}

And MainWindow

和主窗口

public class MainWindow extends JFrame {

    public MainWindow() throws HeadlessException {
        super();
        createGUI();
    }

    private void createGUI() {
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setTitle(getClass().getSimpleName());

        JButton addClientButton = new JButton("Add client");
        addClientButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        AddClient dialog = new AddClient(MainWindow.this);
                        if(dialog.doModal() == AddClient.ID_OK) {

                        }
                    }
                });
            }
        });

        JToolBar toolBar = new JToolBar();
        toolBar.add(addClientButton);

        add(toolBar, BorderLayout.PAGE_START);
    }

    @Override
    public void dispose() {
        super.dispose();
    }
}

回答by Krzysztof Cichocki

If you have it enclosed with Thread, you need to call start() on this thread, if you have Runnable you need to enclose it by Thread class, and then call start().

如果你用Thread封装它,你需要在这个线程上调用start(),如果你有Runnable你需要用Thread类封装它,然后调用start()。

On Runnable and Thread, you can also call run(), but it will run in current Thread.

在 Runnable 和 Thread 上,也可以调用 run(),但它会在当前 Thread 中运行。

Is this your case, because I see part of run() method in your code?

这是你的情况,因为我在你的代码中看到了 run() 方法的一部分?