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

Rolan picture Rolan · Nov 3, 2010 · Viewed 76.6k times · Source

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?

Answer

Jonathan picture Jonathan · Nov 3, 2010

I generally do it like this:

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

The Dialog.showDialog() function looks like this:

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 null if canceled). After processing in the OK/Cancel button method, do this:

setVisible(false);
dispose();

to return control to the showDialog() function.