Java Reference
In-Depth Information
Listing 9-4. A JButton for Use on a JOptionPane
public static JButton getButton(
final JOptionPane optionPane, String text, Icon icon) {
final JButton button = new JButton (text, icon);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
// Return current text label, instead of argument to method
optionPane.setValue(button.getText());
}
};
button.addActionListener(actionListener);
return button;
}
After the specialized JButton is created, you need to place it in a JOptionPane . Unfortunately,
this, too, requires the long form of the JOptionPane usage. The resulting pop-up window is
shown in Figure 9-11.
JOptionPane optionPane = new JOptionPane();
optionPane.setMessage("I got an icon and a text label");
optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
Icon icon = new DiamondIcon (Color.BLUE);
JButton jButton = OptionPaneUtils.getButton(optionPane, "OK", icon);
optionPane.setOptions(new Object[] {jButton} );
JDialog dialog = optionPane.createDialog(source, "Icon/Text Button");
dialog.setVisible(true);
Figure 9-11. Using JOptionPane with a JButton containing a text label and an icon
Tip Setting the value of the JOptionPane with setValue() will hide the option pane when a user selects the
button. If you want to prevent users from closing the window without selecting a button, you can set the default
close operation of the dialog containing the JOptionPane to JDialog.DO_NOTHING_ON_CLOSE . Then
users won't be able to select the close icon from the window adornments. Well, they can select it; it just won't
do anything.
Listening for Property Changes
The JOptionPane class defines the following 11 constants to assist with listening for bound
property changes:
 
Search WWH ::




Custom Search