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?
I dont know if i can explain my method in a cool way... Lets say i need productPrice and ammount from a JDialog whos going to get that info from user, i need to call that from the JFrame.
declare productPrice and ammount as public non-static global variables inside the JDialog.
* this goes inside the dialog's class global scope.
add these lines in the JDialog constructor to ensure modality
* this goes within the dialog's class constructor
lets say your JDialog's class name is 'MyJDialog', when calling do something like this
* this goes in any function within your JFrame and will call JDialog to get infos.
I generally do it like this:
The
Dialog.showDialog()
function looks like this: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 (ornull
if canceled). After processing in the OK/Cancel button method, do this:to return control to the
showDialog()
function.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 :
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
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
Add an interface to your constructor?
}
You should do the opposite by adding a custom method
getValue()
to your customJDialog
.In this way you can ask the value of the dialog from the
JFrame
instead that setting it by invoking something on theJFrame
itself.If you take a look at Oracle tutorial about dialogs here it states
(you can find source of
CustomDialog
to see how they suppose that you will design your custom dialog)