Exercise 23's Window is useless, even compared to Squarer (in Exercise 1) - it doesn't even take a number in and square it. We can do that by using some standard dialogue boxes for text input and message display. Class javax.swing.JOptionPane
has many standard dialogues, eg
showMessageDialog ()
with single OK buttonshowConfirmDialog ()
can have Yes, No, Cancel, etc buttonsshowInputDialog ()
prompts for input and user types in or selects from a drop-down listThere are several constants of the form JOptionPane.xxx_OPTION
where xxx can be CANCEL, OK, OK_CANCEL, YES_NO
, etc
Those calls need parameters of course. Some examples follow.
JOptionPane.showMessageDialog (w, "message");
w is the parent window, in the sense of the windowing system (not superclass).
int response = JOptionPane.showConfirmDialog (w,
new String [] { "line 1", "line 2"},
"title", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE); // icon kind
switch (response)
{
case JOptionPane.YES_OPTION: yesAction (); break;
case JOptionPane.NO_OPTION: noAction (); break;
case JOptionPane.CLOSED_OPTION:; // leave unchanged
}
String response = JOptionPane.showInputDialog (w, "Enter x:");
String response = (String) JOptionPane.showInputDialog (
w, // Parent window
"Destination?", // Prompt
"Select destination", // Title
JOptionPane.QUESTION_MESSAGE, // Icon kind
null, // No icon file
new String [] // Choices
{ "Heathrow", "Gatwick", "Stansted" },
"Heathrow"); // Default choice
NB: There are many different overloaded versions of the common dialogue methods - see the API documentation.