14.Swinging inputs
Swinging inputs
As we saw, using console inputs is quite clumsy, so we need to find an easier way to get our user inputs. Java has a package javax.swing which contains classes that instantiate as forms and windows in the GUI. Let's take a look at a specific class from the javax.swing package called JOptionPane.
JOptionPane makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something. JOptionPane has several methods, and the one we are interested in at the moment is showInputDialog(Object message), which generates an input dialog box which looks something like this:
To use the classes of javax.swing we must import the elements that we need. By way of illustration, here is the previous class ConsoleCylinder adjusted to make use of the showInputDialog(Object message) method of the JOptionPane class:
import javax.swing.JOptionPane;
/**
* Tests using the Cylinder class, and supplying it with
* constructor arguments from an input dialog box.
*/
public class DialogCylinder {
public static void main(String[] args) {
double rad = Double.parseDouble(JOptionPane.showInputDialog(
"Enter the radius of the Cylinder:"));
double ht = Double.parseDouble(JOptionPane.showInputDialog(
"Enter the height of the Cylinder:"));
Cylinder myCylinder = new Cylinder(rad, ht);
System.out.println("\nThe volume of the cylinder is: " +
myCylinder.getVolume());
System.exit(0);
}
}
As you can see, using JOptionPane.showInputDialog(Object message) is really quite simple. Note the following:
- The importation of
javax.swing.JOptionPane. JOptionPane.showInputDialog(Object message)returns a string - once again, we parse and convert the strings to double precision numbers for use as the arguments for theCylinder(aRadius, aHeight)constructor.System.exit(0);- this line terminates the program, and is required because we are using aswingcomponent. Earlier versions of the Java VM do not necessarily clear up completely after using a swing component; in these versions if you don't include this statement, you will see that the code hangs in the console without returning execution to the console in the usual way. You can get the code to terminate by pressingCtrl+Con the keyboard, but this is not very elegant. Comment out theSystem.exit(0);instruction if you'd like to see what happens if you don't use it. Newer versions of Java will clean up after your code, but this still produces a brief pause in the proceedings before the application safely terminates. (TheSystem.exit(0);instruction in fact causes the VM to immediately destroy all objects, clear out the memory, and shut down completely - no further instructions can be executed by the VM in that session.)
Compile and test your code.
© G. Hearn, & University of the Western Cape, 2006






