Java Reference
In-Depth Information
Figure 9-9. Using JOptionPane with a complex message property
Adding Components to the Message Area
If you were to display the pop-up in Figure 9-9, you would notice a slight problem. The option
pane doesn't know about the embedded JSlider setting, unlike the way it automatically knows
about input to the automatic JTextField , JComboBox , or JList components. If you want the
JOptionPane (or for that matter, any input component) to get the JSlider value, you need to
have your input component change the inputValue property of the JOptionPane . When this
value is changed, the option pane tells the pop-up window to close because the JOptionPane
has acquired its input value.
Attaching a ChangeListener to the JSlider component enables you to find out when its
value has changed. Adding yet another method to the OptionPaneUtils class shown earlier in
Listing 9-1 allows you to reuse this specialized JSlider with multiple JOptionPane objects more
easily. The important method call is shown in boldface in Listing 9-3. A similar line would need
to be added for any input component that you wanted to place within a JOptionPane . The line
notifies the option pane when the user has changed the value of the input component.
Listing 9-3. Helper Method for Creating a JSlider for Use in a JOptionPane
public static JSlider getSlider(final JOptionPane optionPane) {
JSlider slider = new JSlider();
slider.setMajorTickSpacing (10);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
JSlider theSlider = (JSlider)changeEvent.getSource();
if (!theSlider.getValueIsAdjusting()) {
optionPane.setInputValue(new Integer(theSlider.getValue()));
}
}
};
slider.addChangeListener(changeListener);
return slider;
}
Now that the specialized JSlider is created, you need to place it on a JOptionPane . This
requires the manual creation of a JOptionPane component and, surprisingly, doesn't require
 
Search WWH ::




Custom Search