The JOptionPane Class

You can also obtain input from the user using the JOptionPane class. Of course, one first needs to import the appropriate package to use it. This means adding the following in the appropriate spot in your program:

import javax.swing.JOptionPane;

Then, later in your code, you can invoke one of the methods of the JOptionPane class to get information from the user. For example, you might use

String s = JOptionPane.showInputDialog("Enter a year: ");

We should -- more generally, of course -- change the "Enter a year" prompt to something more appropriate for the information we wish to collect from the user in a different context.

The result of the statement above will be that the program displays the following dialog box (Note: the dialog box that gets displayed on a Windows machine may look a bit different than the same dialog box on a Mac running OS X, but you should still see two buttons and the same text):

If we want more control over the content of the dialog box, we can call the same method with additional parameters, like the following:

String s = JOptionPane.showInputDialog(null,
             "Enter a year: ",
             "My Query",

which yields:

You can see that the title of the dialog box has changed to "My Query", and the style of the dialog box (at least to the extent that the icon has changed) has also been modified. The style of a dialog box is determined by the last parameter given to the showInputDialog() method call. The possible values are:

(Note: Since we didn't give any information to the user in the last example, we probably should not have used the INFORMATION_MESSAGE style. A QUESTION_MESSAGE would have been more appropriate, and would have given us the same icon we saw in the first picture.)

You may have noticed that the first parameter passed to the method was "null". We will talk more about this later, but for now, think of "null" as something to pass to a method when you have to pass something, but don't really have anything to pass. In our example, the first parameter is supposed to represent a "parent component" (again, more on what that is later), but we don't have one in this program, so we give pass "null" as a "space-holder" of sorts.

As the other styles mentioned above suggest, we can use the JOptionPane class to do more than just get input from the user. We can also use it to display messages to the user. For example, the following code:

  "Chris Columbus sailed the ocean blue.",
  "In 1942...",  

displays the dialog box

This just scratches the surface, however. If you want to know all of the other things the JOptionPane class can do, check out the class documentation in the Java API.