Java 如何将 JDialog 框中的值返回到父 JFrame?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4089311/
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-08-14 11:29:49  来源:igfitidea点击:

How can I return a value from a JDialog box to the parent JFrame?

javaswingreturn-valuejdialog

提问by Rolan

I have created a modal JDialog box with a custom drawing on it and a JButton. When I click the JButton, the JDialog box should close and a value should be returned.

我创建了一个模态 JDialog 框,上面有一个自定义绘图和一个 JButton。当我单击 JButton 时,JDialog 框应该关闭并且应该返回一个值。

I have created a function in the parent JFrame called setModalPiece, which receives a value and sets it to a local JFrame variable.

我在父 JFrame 中创建了一个名为 setModalPiece 的函数,它接收一个值并将其设置为本地 JFrame 变量。

The problem is that this function is not visible from the JDialog box (even though the JDialog box has a reference to the parent JFrame).

问题是这个函数在 JDialog 框中是不可见的(即使 JDialog 框有对父 JFrame 的引用)。

Two questions: 1) Is there a better way to return a value from a JDialog box to its parent JFrame?

两个问题:1) 是否有更好的方法将 JDialog 框中的值返回到其父 JFrame?

2) Why can't the reference to the JFrame passed to the JDialog be used to access my JFrame function setModalPiece?

2) 为什么不能使用对传递给 JDialog 的 JFrame 的引用来访问我的 JFrame 函数 setModalPiece?

采纳答案by Hyman

You should do the opposite by adding a custom method getValue()to your custom JDialog.

您应该通过将自定义方法添加getValue()到您的自定义JDialog.

In this way you can ask the value of the dialog from the JFrameinstead that setting it by invoking something on the JFrameitself.

通过这种方式,您可以从对话框中询问对话框的值,JFrame而不是通过调用JFrame自身上的某些内容来设置它。

If you take a look at Oracle tutorial about dialogs hereit states

如果您在此处查看有关对话框的 Oracle 教程,它会指出

If you're designing a custom dialog, you need to design your dialog's API so that you can query the dialog about what the user chose. For example, CustomDialog has a getValidatedText method that returns the text the user entered.

如果您正在设计自定义对话框,则需要设计对话框的 API,以便您可以查询对话框有关用户选择的内容。例如,CustomDialog 有一个 getValidatedText 方法,它返回用户输入的文本。

(you can find source of CustomDialogto see how they suppose that you will design your custom dialog)

(您可以找到来源CustomDialog以了解他们如何假设您将设计自定义对话框)

回答by Jonathan

I generally do it like this:

我一般是这样做的:

Dialog dlg = new Dialog(this, ...);
Value result = dlg.showDialog();

The Dialog.showDialog()function looks like this:

Dialog.showDialog()函数如下所示:

ReturnValue showDialog() {
    setVisible(true);
    return result;
}

Since setting visibility to true on a JDialog is a modal operation, the OK button can set an instance variable (result) to the chosen result of the dialog (or nullif canceled). After processing in the OK/Cancel button method, do this:

由于在 JDialog 上将可见性设置为 true 是一种模态操作,因此 OK 按钮可以将实例变量 ( result)设置为对话框的所选结果(或者null如果取消)。在确定/取消按钮方法中处理后,执行以下操作:

setVisible(false);
dispose();

to return control to the showDialog()function.

将控制权返回给showDialog()函数。

回答by Rajshri

When you pass any value to JFrame to JDialog then create parametrized constructor of jdialog and in jframe whenever you want to call. e.g. The parametrized constructor like :

当您将任何值传递给 JFrame 到 JDialog 时,然后在您想要调用时创建 jdialog 和 jframe 的参数化构造函数。例如参数化的构造函数,如:

 public EditProduct(java.awt.Frame parent, boolean modal, int no) {
      //int no is number of product want to edit.
      //Now we can use this pid in JDialog and perform whatever you want.
}

When you want to pass values from JDialog to JFrame create a bean class with set and get method the the values using vector and get these values in jframe. More info

当您想将值从 JDialog 传递到 JFrame 时,创建一个带有 set 和 get 方法的 bean 类,这些值使用向量并在 jframe 中获取这些值。 更多信息

回答by Felype

I don't know if I can explain my method in a cool way... Let's say I need productPrice and amount from a JDialog whos going to get that info from user, I need to call that from the JFrame.

我不知道我是否可以用一种很酷的方式解释我的方法......假设我需要从 JDialog 获取 productPrice 和 amount ,他将从用户那里获取该信息,我需要从 JFrame 调用它。

declare productPrice and ammount as public non-static global variables inside the JDialog.

将 productPrice 和 ammount 声明为 JDialog 中的公共非静态全局变量。

public float productPrice;
public int amount;

* this goes inside the dialog's class global scope.

* 这进入对话框的类全局范围内。

add these lines in the JDialog constructor to ensure modality

在 JDialog 构造函数中添加这些行以确保模式

super((java.awt.Frame) null, true);
setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);

* this goes within the dialog's class constructor

* 这在对话框的类构造函数中

let's say your JDialog's class name is 'MyJDialog' when calling do something like this

假设您的 JDialog 的类名是“MyJDialog”,当调用做这样的事情

MyJDialog question = new MyJDialog();
MyJDialog.setVisible(true); 
// Application thread will stop here until MyJDialog calls dispose();
// this is an effect of modality
//
// When question calls for dispose(), it will leave the screen,
// but its global values will still be accessible.
float myTotalCostVar = question.productPrice * question.ammount;
// this is acceptable.
// You can also create public getter function inside the JDialog class,
// its safer and its a good practice.

* this goes in any function within your JFrame and will call JDialog to get infos.

* 这会出现在 JFrame 中的任何函数中,并将调用 JDialog 来获取信息。

回答by guitar_freak

Here is how I usually do it. I wasn't sure, that's why I've created that post:

这是我通常的做法。我不确定,这就是我创建该帖子的原因:

Returning value from JDialog; dispose(), setVisible(false) - example

从 JDialog 返回值;dispose(), setVisible(false) - 示例

回答by Wil_Ryan

Add an interface to your constructor?

向构造函数添加接口?

public class UploadConfimation extends JDialog {

private final JPanel contentPanel = new JPanel();


public interface GetDialogResponse{
    void GetResponse(boolean response);
}



/**
 * Create the dialog.
 */
public UploadConfimation(String title, String message, GetDialogResponse result) {
    setBounds(100, 100, 450, 300);
    setTitle(title);
    getContentPane().setLayout(new BorderLayout());
    contentPanel.setLayout(new FlowLayout());
    contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
    getContentPane().add(contentPanel, BorderLayout.CENTER);
    {
        JLabel lblMessage = new JLabel(message);
        contentPanel.add(lblMessage);
    }
    {
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
        getContentPane().add(buttonPane, BorderLayout.SOUTH);
        {
            JButton okButton = new JButton("YES");
            okButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    result.GetResponse(true);
                    dispose();
                }
            });
            buttonPane.add(okButton);
            getRootPane().setDefaultButton(okButton);
        }
        {
            JButton cancelButton = new JButton("NO");
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    result.GetResponse(false);
                    dispose();
                }
            });
            buttonPane.add(cancelButton);
        }
    }
}

}

}