Search code examples
javaswingreturn-valuejdialog

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


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.

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

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).

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

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


Solution

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

    In this way you can ask the value of the dialog from the JFrame instead that setting it by invoking something on the JFrame itself.

    If you take a look at Oracle tutorial about dialogs here it states

    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.

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