问题
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