I have a JSplitPane which when shown should split the pane by 50%.
Now on giving an argument of 0.5 (as suggested) to setDividerLocation, Java seems to treat it as a normal number instead of a percentage. As in, the divider, instead of going to the middle of the pane, is almost at the start of the left pane (the pane is vertically split). Any work arounds?
Am I missing something? There seem to be a lot of rather convoluted answers to this question... but I think a simple setResizeWeight(0.5) would solve the issue ... it's described in the SplitPane Tutorial
The setDividerLocation( double ) method only works on a "realized" frame, which means after you've packed or made the frame visible.
The setDividerLocation( int ) method can be used at any time.
You can only set the split pane divider's location as a percentage when the split pane is visible. You can tap into the split pane owner's events to determine when its OK to set the divider's location. For example:
public class MyFrame extends JFrame {
public MyFrame() {
final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
// ... set up the split pane, and add to the frame ...
// Listen for the frame's "shown" event.
addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent componentEvent) {
// Set the divider location to 20%.
// This works because we know the pane is visible.
splitPane.setDividerLocation(.2);
// Stop listening for "shown" events.
removeComponentListener(this);
}
});
pack();
}
}
this fixes it:
public class JSplitPane3 extends JSplitPane {
private boolean hasProportionalLocation = false;
private double proportionalLocation = 0.5;
private boolean isPainted = false;
public void setDividerLocation(double proportionalLocation) {
if (!isPainted) {
hasProportionalLocation = true;
this.proportionalLocation = proportionalLocation;
} else {
super.setDividerLocation(proportionalLocation);
}
}
public void paint(Graphics g) {
super.paint(g);
if (!isPainted) {
if (hasProportionalLocation) {
super.setDividerLocation(proportionalLocation);
}
isPainted = true;
}
}
}
If you're happy for the divider to move to the middle every time you resize the pane, you could add a ComponentListener and have its componentResized method call setDividerLocation(0.5).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With