In my Swing app, users can click a button to open a dialog panel and enter some values, then they can click "Ok" on that panel to close it and return to the main program, but how can I pass the values they enter to the main program without saving them to a file first ?
views:
309answers:
5There are a couple things you could do:
- You could create an Observer/Observable relationship between your app and the dialog, and make the dialog publish an event when the dialog closes with the values in the event.
- You could maintain a handle to your dialog in your app, and when you call
setVisible(false)
on dialog, you can query the dialog for its data.
The UI should usually be layered upon the underlying application. (IMO, the UI should itself be split into layers, but that another rant.) Pass in a relevant part of your application to the creation of your UI. When you are ready for values to go from the UI to the application (which could be an OK button on a multi-page dialog, down to every keystroke), push the data to the application component.
I would suggest MVC(Model-view-controller) design. So dialog will be you view and possibly controller. But have to have a domain class which will be your model. For example, if the dialog is created to edit personal data, then you can have class called Person which will hold the data. The dialog should be designed in the way so you can set and get a Person from it.
Rather than using just the poor Java Observable
/Observer
API, I'd rather advise you take a look at an "Event Bus", which should be particularly suited for your situation.
Two implementations of Event Buses:
- EventBus very general event bus, can be used in any situation
- GUTS Event Bus specific to Guice dependency injection library
One of these should help you with your current problem.
May be you would like to try this solution:
class MyDialog {
private static String[] returnValues = new String[10]
private static MyDialog dialog;
private MyDialog() {
initDialog()
}
private void closeDialog()
{
dispose();
}
private initDialog()
{
//....
btnOk = new JButton("OK");
jTextField1 = new JTextField();
...
jTextField10 = new JTextField();
...
ActionListener btnOK_click = new ActionListener() {
public void actionPerformed(ActionEvent e)
{
returnValues[0] = jTextField1.getText();
...
returnValues[9] = jTextField10.getText();
closeDialog();
}
}
btnOk.addActionListener(btnOk_click);
}
public static String[] showMyDialog() {
dialog = new MyDialog();
dialog.setVisible(true);
return returnValues;
}
}