Java Reference
In-Depth Information
Note Including the characters \ n in the message text will force the message to be displayed on multiple
lines. Then it's your responsibility to count the number of characters in each message line. The message text
in a JOptionPane can be formatted with HTML tags, as it can in other Swing components.
Understanding the Message Property
In all the previous examples in this chapter of using the message argument to the JOptionPane
constructors and using the factory methods, the message was a single string. As described
earlier in the “The JOptionPane Message Argument” section, this argument doesn't need to be
a single string. For instance, if the argument were an array of strings, each string would be on a
separate line. This eliminates the need to use the narrow JOptionPane , but requires you to
count the characters yourself. However, because you're splitting apart the message, you can
use one of the 25 factory methods. For instance, the following source creates the pop-up
window shown in Figure 9-8.
String multiLineMsg[] = { "Hello,", "World"} ;
JOptionPane.showMessageDialog(source, multiLineMsg);
Figure 9-8. Using JOptionPane with a string array
Caution If you manually count the characters within a long message to split it into a multiline message,
the output may not be the best. For instance, when using a proportional font in which character widths vary,
a line of 20 w characters would be much wider than a line of 20 i or l characters.
The message argument not only supports displaying an array of strings, but it also can
support an array of any type of object. If an element in the array is a Component , it's placed
directly into the message area. If the element is an Icon , the icon is placed within a JLabel , and
the JLabel is placed into the message area. All other objects are converted to a String , placed
into a JLabel , and displayed in the message area, unless the object is itself an array; in that case,
these rules are applied recursively.
To demonstrate the possibilities, Figure 9-9 shows off the true capabilities of the JOptionPane .
The actual content isn't meant to show anything in particular—just that you can display a lot
of different stuff. The message argument is made up of the following array:
Object complexMsg[] = {
"Above Message", new DiamondIcon(Color.RED), new JButton("Hello"),
new JSlider(), new DiamondIcon(Color.BLUE), "Below Message"} ;
 
Search WWH ::




Custom Search