Java Reference
In-Depth Information
Listing 9-2. Helper Method to Create a Narrow JOptionPane
public static JOptionPane getNarrowOptionPane(int maxCharactersPerLineCount) {
// Our inner class definition
class NarrowOptionPane extends JOptionPane {
int maxCharactersPerLineCount;
NarrowOptionPane(int maxCharactersPerLineCount) {
this.maxCharactersPerLineCount = maxCharactersPerLineCount;
}
public int getMaxCharactersPerLineCount() {
return maxCharactersPerLineCount;
}
}
return new NarrowOptionPane(maxCharactersPerLineCount);
}
Once the method and new class are defined, you can create an option pane of a specified
character width, manually configure all the properties, place it in a pop-up window, show it,
and then determine the user's response. The following source demonstrates using these new
capabilities, with the long message trimmed a bit.
String msg = "this is a really long message ... this is a really long message";
JOptionPane optionPane = OptionPaneUtils.getNarrowOptionPane(72);
optionPane.setMessage(msg);
optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = optionPane.createDialog(source, "Width 72");
dialog.setVisible(true);
Figure 9-7 demonstrates what would happen if you didn't change the
maxCharactersPerLineCount property. Figure 9-7 also shows the new narrow JOptionPane .
Figure 9-7. Default JOptionPane and a narrow JOptionPane
Although this seems like a lot of work, it's the best way to create multiline option panes,
unless you want to manually parse the message into separate lines.
Search WWH ::




Custom Search