GridbagLayout within ScrollPane Java Swing

那年仲夏 提交于 2019-12-25 07:38:34

问题


I'd just made a layout in GridBagLayout for a split pane. Worked perfectly and looked right.

I then needed to then add a scroll bar vertically only. Hence I have done that now. However the layout doesn't 'size' like before. It now stretches across rather sticking to the area of the pane shown.

JSplitPane VPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,(new class1()),new JScrollPane(new class2(),ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER));

I need to make it look like it did before. Any ideas?


回答1:


All you've done is "hide" the horizontal scroll bar. This will have no effect on the view port that is managing your component.

Try wrapping your existing layout in a Scrollable interface. If you don't want to implement one your self, you could use a wrapper container instead...

public class ScrollableWrapper extends JPanel implements Scrollable {

    private Component wrapper;

    public ScrollableWrapper(Component wrapper) {
        setLayout(new BorderLayout());
        add(wrapper);
        this.wrapper = wrapper;
    }

    @Override
    public Dimension getPreferredScrollableViewportSize() {
        return wrapper.getPreferredSize();
    }

    @Override
    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
        return 64;
    }

    @Override
    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
        return 64;
    }

    @Override
    public boolean getScrollableTracksViewportWidth() {
        return true;
    }

    @Override
    public boolean getScrollableTracksViewportHeight() {
        return false;
    }

}

Then, we you add it to your scroll pane...

JSplitPane VPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,new class1(),new JScrollPane(new ScrollableWrapper(class2())));


来源:https://stackoverflow.com/questions/13466540/gridbaglayout-within-scrollpane-java-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!