In a JSplitPane
, you have the setOneTouchExpandable
method which provides you with 2 buttons to quickly fully hide or full show the JSplitPane
.
My question is how can you programmatically "click" the hide button on the JSplitPane
?
I may have wrongly explained myself. I want the splitpane to show only one of the 2 components at start (this is what i mean by clicking).
This works:
import javax.swing.*;
class SplitPaneDefault {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JSplitPane sp = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
new JTree(),
new JTree());
sp.setOneTouchExpandable(true);
sp.setDividerLocation(0.0);
JOptionPane.showMessageDialog(null, sp);
}
});
}
}
but replacing 0.0
with 1.0
doesn't hide the right component. This is my problem!
You can simply use this:
or.
depending on wheter yourwant to hide the left component first or the right component.
Read the fine manual and solve the problem.
@0__'s answer is a hint that you should be using the
AncestorListener
to set the divider location, and have it taken into account (ComponentListener
is not enough, I'm not sure why).However, it's not sufficient: if the split plane somehow gets resized (e.g. because its layout manager decided it should, when the frame has been resized), a tiny fraction of the component you wanted to hide will still show. That's due to the component minimum size not being zero. It can be addressed by zeroing it with
setMinimumSize(new Dimension())
(as explained in that other answer), but if that's not an option, you can hack into the split pane UI:If you're using the standard
BasicSplitPaneUI
, you can hack itskeepHidden
boolean field and force it totrue
, so the divider will stick to either side:Here is another solution, maybe a little bit dirty, but it works ;) I hope the code speaks for itself.
And an example how to use it:
Working around the problem that
setDividerLocation(1.0)
doesn't work until the frame has become displayable, one can use anAncestorListener
: