how can you programmatically set the JSplitPane to hide the right/bottom component when OneTouchExpandable is set to true?

前端 未结 5 1089
遥遥无期
遥遥无期 2021-01-06 06:30

In a JSplitPane, you have the setOneTouchExpandable method which provides you with 2 buttons to quickly fully hide or full show the JSplitPan

5条回答
  •  温柔的废话
    2021-01-06 06:54

    @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 its keepHidden boolean field and force it to true, so the divider will stick to either side:

    sp.addAncestorListener(new AncestorListener() {
        @Override
        public void ancestorAdded(AncestorEvent event) {
            sp.setDividerLocation(1.0); // Divider is positioned
            Field m = BasicSplitPaneUI.class.getDeclaredField("keepHidden");
            m.setAccessible(true);
            m.set(sp.getUI(), true); // Divider position will stick
            //sp.removeAncestorListener(this); // Uncomment for a one-shot event
        }
    
        @Override public void ancestorRemoved(AncestorEvent event) { }
        @Override public void ancestorMoved(AncestorEvent event) { }
    });
    

提交回复
热议问题