Java Reference
In-Depth Information
Resetting the Viewport Position
At times, you may want to move the contents of the inner view to the upper-left corner of the
JScrollPane
. This change may be needed because the view changed, or because some event
happened that requires the viewport component to return to the origin of the
JScrollPane
.
The simplest way of moving the view is to adjust the position of the scrollbar thumbs of the
JScrollPane
. Setting each scrollbar to its minimum value effectively moves the view of the
component to the component's upper-left corner. The
ActionListener
shown in Listing 11-4
can be associated with a button on the screen or in the corner of the
JScrollPane
, causing the
contents of the
JScrollPane
to return to their origin.
Listing 11-4.
Action to Move JScrollPane to Top
import java.awt.event.*;
import javax.swing.*;
public class JScrollPaneToTopAction implements ActionListener {
JScrollPane scrollPane;
public JScrollPaneToTopAction(JScrollPane scrollPane) {
if (scrollPane == null) {
throw new IllegalArgumentException(
"JScrollPaneToTopAction: null JScrollPane");
}
this.scrollPane = scrollPane;
}
public void actionPerformed(ActionEvent actionEvent) {
JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar();
JScrollBar horizontalScrollBar = scrollPane.getHorizontalScrollBar();
verticalScrollBar.setValue(verticalScrollBar.getMinimum());
horizontalScrollBar.setValue(horizontalScrollBar.getMinimum());
}
}
Customizing a JScrollPane Look and Feel
Each installable Swing look and feel provides a different
JScrollPane
appearance and set
of default
UIResource
values for the component. Figure 11-17 shows the appearance of the
JScrollPane
component for the preinstalled set of look and feel types. With a
JScrollPane
, the
primary differences between the look and feel types are related to the scrollbar's appearance
and border around the viewport.
The available set of
UIResource
-related properties for a
JScrollPane
is shown in Table 11-9.
For the
JScrollPane
component, there are ten different properties. Changing the properties
related to the
JScrollBar
will also affect appearance when a scrollbar in a
JScrollPane
is visible.