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?
JFrame is a normal window with its normal buttons (optionally) and decorations. JDialog on the other side does not have a maximize and minimize buttons and usually are created with JOptionPane static methods, and are better fit to make them modal (they block other components until they are closed).
I would recommend using dispose() to release resources and free up memory. If you want to show the dialog again, simply invoke setVisible(true) . It's important to note that when the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate.
In a Java JFrame, we can add an instance of a JButton class, which creates a button on the frame as follows in the code below: //add a button. JButton b = new JButton("Submit");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With