Java Reference
In-Depth Information
This version of the method provides a list of choices in a drop-down list box. The items from which to choose
are passed as the sixth argument as an array and they can be of any class type. The initial selection to be
displayed when the dialog is first displayed is specified by the seventh argument. Whatever is chosen when
the OK button is clicked will be returned as type Object , and, if the Cancel button is clicked, null will be
returned. You can specify your own icon to replace the default icon by passing a reference of type Icon as
the fifth argument. The following statements display the dialog shown:
String[] choices = {"Money", "Health", "Happiness", "This", "That", "The Other"};
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 we are using type String , but the selections could be
type Icon , or whatever you want.
Using a Dialog to Create Text Elements
It would be good if our Sketcher program also 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 we create text elements. We can use one of the showInputDialog() methods
for this, but first we need to add a Text menu item to the Elements menu, and we will need a class to
represent text elements, the Element.Text class of course, with Element as a base class. Let's start
with the Element.Text class.
Text is a little tricky. For one thing we can't treat it just like another element. There is no object that
implements the Shape interface that represents a text string so, unless we want to define one, we can't
use the draw() method for a graphics context to display text. We have to use the drawString()
method. We'll also have to figure out the bounding rectangle for the text on screen for ourselves. With
Shape objects you could rely on the getBounds() method supplied by the 2D shape classes in
java.awt.geom , but with text you're on your own.
Ideally we want to avoid treating text elements as a special case. Having many tests for types while
we're drawing a sketch in the paint() method for the view generates considerable processing
overhead that we would be better off without. One way around this is to make every element draw
itself. We could implement a polymorphic method in each element class, draw() say, and pass a
Graphics2D object to it. Each shape or text element could then figure out how to draw itself. The
paint() method in the view class would not need to worry about what type of element was being
drawn at all.
Search WWH ::




Custom Search