Java Reference
In-Depth Information
of 10. This default model offers a range of only 0 through 90. You can also explicitly set the
orientation to JScrollBar.HORIZONTAL or JScrollBar.VERTICAL . If you don't like the initial
model settings provided by the other two constructors, you need to explicitly set everything
yourself. If the data elements aren't properly constrained, as described in the previous section
about BoundedRangeModel , an IllegalArgumentException will be thrown, causing the JScrollBar
construction to be aborted.
Surprisingly missing from the list of constructors is one that accepts a BoundedRangeModel
argument. If you have a model instance, you can either call setModel(BoundedRangeModel
newModel) after creating the scrollbar or get the individual properties from the model when
creating the scrollbar, as follows:
JScrollBar aJScrollBar =
new JScrollBar (JScrollBar.HORIZONTAL, aModel.getValue(), aModel.getExtent(),
aModel.getMinimum(), aModel.getMaximum())
Tip Starting with the 1.3 release of the J2SE platform, scrollbars do not participate in focus traversal.
Handling Scrolling Events
Once you've created your JScrollBar , it's necessary to listen for changes if you're interested in
when the value changes. There are two ways of listening: the AWT 1.1 event model way and the
Swing MVC way. The AWT way involves attaching an AdjustmentListener to the JScrollBar .
The MVC way involves attaching a ChangeListener to the data model. Each works equally well,
and both are notified if the model changes programmatically or by the user dragging the
scrollbar thumb. The latter offers more flexibility and is a good choice, unless you're sharing a
data model across components and need to know which component altered the model.
Listening to Scrolling Events with an AdjustmentListener
Attaching an AdjustmentListener to a JScrollBar allows you to listen for the user to change the
setting of the scrollbar. The following code fragments, used for the example shown later in
Figure 12-3, show how to attach an AdjustmentListener to a JScrollBar to listen for the user
adjusting the value of the JScrollBar .
First, define the appropriate AdjustmentListener that simply prints out the current value
of the scrollbar:
AdjustmentListener adjustmentListener = new AdjustmentListener() {
public void adjustmentValueChanged (AdjustmentEvent adjustmentEvent) {
System.out.println ("Adjusted: " + adjustmentEvent.getValue());
}
};
After you've created the listener, you can create the component and attach the listener:
JScrollBar oneJScrollBar = new JScrollBar (JScrollBar.HORIZONTAL);
oneJScrollBar.addAdjustmentListener(adjustmentListener);
 
Search WWH ::




Custom Search