Building a Java GUI - Containers |
Written by Mike James | |||||
Page 4 of 4
Communicating With A DialogIn many cases a dialog box is used to get some data from the user. This raises the question of how to get the data back from a dialog box to the program that created it. This is a surprisingly difficult question because it raised lots of advanced design ideas and programmers can argue about elegant ways of doing the same job. For simplicity I'm going to concentrate on getting data back from a modal dialog box in the simplest possible way. This at least gives you a chance to see if you understand some very basic object oriented ideas. When you show a modal dialog box the program that used the
instruction is paused and it waits for the user to dismiss the dialog box. The key to getting data from the dialog box is to realize that the dialog box object doesn't vanish when the users closed the visible dialog box on the screen. What this means is that if you add a public property or better a "getter" method then the parent program can access the values stored in the dialog box. For example, if you add the following public method to MyDialog
Then in the program that calls it the value of the third text field can be retrieved using:
This is one of the reasons why modal dialog boxes are so easy to use to gather data - the parent program pauses while the user fills in the data and the dialog box object isn't destroyed when the user finished with the on-screen dialog. This allows the parent program to gather the data via the dialog box's properties. Notice that as the dialog object exists before it is made visible to the user the parent program can use setter methods to set values in the dialog in the same way before calling setVisible(true). There are other more elegant ways of doing both jobs. The Standard DialogsBefore leaving this topic it is worth mentioning that fact that Java has lots of standard dialog boxes ready for you to use. It would be a waste of a lot of time to use the jDialog class to recreate any of these. For example there is a standard file open, color picker and a range of simple alert type dialogs. Look up jOptionPane., jFileChooser and jColorChooser. Summary
Modern Java
|