Java Reference
In-Depth Information
String[] choices = {"Money", "Health", "Happiness",
"Power", "Notoriety", "Anonymity"};
String input = (String)JOptionPane.showInputDialog(null, "Choose now...",
"The Choice of a Lifetime",
JOptionPane.QUESTION_MESSAGE,
null, // Use default icon
choices, // Array of choices
choices[1]); // Initial choice
Note that you have to cast the reference returned by this version of the
showInputDialog()
method to
the type of choice value you have used. Here you are using type
String
, but the selections could be type
Icon
, or whatever you want. Clicking the down arrow displays the list of choices.
USING A DIALOG TO CREATE TEXT ELEMENTS
It would be good if our Sketcher program provided a means of adding text to a picture — after all, you might
want to put your name to a sketch. A dialog is the obvious way to provide the mechanism for entering the
text when you create text elements, and the one that generated
Figure 20-6
is a good candidate. This could
be generated by one or other of the mouse event handler methods to get input for a text element. You must
put the infrastructure in place to deal with text elements, though.
For consistency with other types of elements in Sketcher, you need to add a
Text
menu item to the
Ele-
ments
menu and a toolbar button. You also have to define a class to represent text elements, which is the
Element.Text
class with
Element
as the base class. Let's start with the GUI elements, as they are quite
easy to implement.
Defining the Menu Item and Toolbar Button for Text
To start, add a
textAction
member of type
TypeAction
to the
SketcherFrame
class:
private TypeAction lineAction, rectangleAction, circleAction,
curveAction, textAction;
You can initialize the
Action
object for text in the
createElementTypeAction()
method in
Sketcher-
Frame
: