Friday, June 27, 2008

Pop-up Window with Return Value

Trick
In this post a trick is presented: possibility to return object from a pop-up dialog.

It can be useful to
  • select and return an element of list from a pop-up dialog
  • create a new object in a pop-up dialog and return it
  • edit an object in a pop-up dialog and return it
Participants
Caller - the place, where the pop-up window is opened and the returned data is processed.
Dialog - this is the pop-up window, what produces the return object.

Step 1: Creating the dialog
Create a GUI window, what extends the javax.swing.JDialog class, like this:



My sample dialog creates and returns a String instance from a TextField.

Step 2: Extend the dialog code
First add a new class member to the created dialog class:

private <ReturnObjectClass> returnValue;

where the <ReturnObjectClass> is the class of the object, what our pop-up window returns, in my case:

private String returnValue;

Now write the actions to the buttons.
Cancel button close the window and return null:

returnValue =null;
dispose();

Return button close the window and return the new String:

returnValue = jTextField1.getText();
dispose();

At least construct the method, what return the created object:

public String getValue() {
this.setVisible(true);
return returnValue;
}

Step 3: Creating the caller
Create a class, named Main, and put the following code:

public static void main(String[] args) {
String s = new GetStringDialog(null, true).getValue();
System.out.println("Dialog returned with: " + s);
}

After you run this program, the pop-up dialog is showed and after clicking the Return button the typed string is written to the console.

Downloads
You can download sample code here as NetBeans project.