Java Reference
In-Depth Information
Figure 11-6.
Adding left/right buttons to a vertical JSplitPane
The code is more understandable if the
setTopComponent()
and
setBottomComponent()
methods are used with better variable names:
JComponent topButton = new JButton("Left");
JComponent bottomButton = new JButton("Right");
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPane.setTopComponent(topButton);
splitPane.setBottomComponent(bottomButton);
Moving the JSplitPane Divider
Initially, the divider is shown below or to the right of the preferred size of the top or left
component. At any time, you can reset the divider position to that position by calling the
resetToPreferredSizes()
method of
JSplitPane
. If you want to programmatically position the
divider, you can change the
dividerLocation
property with
setDividerLocation(newLocation)
.
This property can be changed to an
int
position, representing an absolute distance from the
top or left side, or it can be set to a
double
value between 0.0 and 1.0, representing a percentage
of the
JSplitPane
container width.
■
Caution
Changing the property setting to a
double
value outside the range of 0.0 and 1.0 results in an
IllegalArgumentException
being thrown.
If you want to set the divider location, you must wait for the component to be realized.
Essentially, that means it must be visible. While there are roundabout ways of doing this, the
most direct way is to attach a
HierarchyListener
to the
JSplitPane
and watch for when the
HierarchyEvent
is of type
SHOWING_CHANGED
. This is demonstrated in the following code fragment,
changing the divider location to 75%.
HierarchyListener hierarchyListener = new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
long flags = e.getChangeFlags();
if ((flags & HierarchyEvent.SHOWING_CHANGED) ==
HierarchyEvent.SHOWING_CHANGED) {
splitPane.setDividerLocation(.75);
}
}
};
splitPane.addHierarchyListener(hierarchyListener);