Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 634
Rolan Avatar asked Nov 03 '10 16:11

Rolan


People also ask

What is the difference between JFrame and JDialog?

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

How do I dispose of JDialog in Java?

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.

Can you add JButton to JFrame?

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");


1 Answers

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.

like image 138
Jonathan Avatar answered Sep 23 '22 23:09

Jonathan