28.12.2012 Views

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

Core JFC Java Foundation Classes 2nd edition - Read

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Basic Dialogs 777<br />

each entry in the list is turned into a string by calling its toString method<br />

and the result is added to the combo box or list. However, when the user<br />

makes a selection, the value returned by showInputDialog is not the string<br />

that the user saw but the Object that generated that string. This can be<br />

demonstrated by creating a list of Font objects instead of Strings:<br />

Font selectedFont = (Font)JOptionPane.showInputDialog(f,<br />

"Please select a font:",<br />

"Background Color Selection",<br />

JOptionPane.PLAINJMESSAGE,<br />

null,<br />

choices,<br />

choices[0] );<br />

public static final Font [] choices = {<br />

new Font("Dialoglnput", Font.PLAIN, 12),<br />

new Font("Dialoglnput", Font.PLAIN, 14),<br />

new Font("Dialog", Font.PLAIN, 12),<br />

new Font("Dialog", Font.BOLD, 12),<br />

new Font("Serif", Font.ITALIC, 12),<br />

new Font("Serif", Font.BOLD [ Font.ITALIC, 12)<br />

};<br />

The dialog box that appears when you execute the command:<br />

java <strong>JFC</strong>Book.Chapter7.InputDialogExample3<br />

and which is shown in Figure 7-8 contains string versions of the Font<br />

objects. Unfortunately, the result of applying toString to a Font does not<br />

produce a very useful result (except perhaps to the programmer), but it does<br />

clearly show that the combo box contains a representation of the objects that<br />

it was passed.<br />

Figure 7-8 The JOptionPane input dialog with an object rather than a string.<br />

Choosing a font description and pressing OK causes showInputDialog to<br />

return and the result is printed. The output is, not surprisingly, the same as<br />

the entry that was selected from the dialog. It is clear, however, that what was

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!