我有一个简单的JPanel,上面有一个JScrollPane(根据需要带有垂直滚动条)。
东西被添加到JPanel(或从JPanel中删除),当它超出面板底部时,我希望JScrollPane根据需要自动向下滚动到底部,或者如果一些组件离开面板,则向上滚动。
我该怎么做?我想我需要某种监听器,每当JPanel高度改变时,它就会被调用?还是有像JScrollPanel.setAutoScroll(true)
这样简单的东西?
scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
e.getAdjustable().setValue(e.getAdjustable().getMaximum());
}
});
这将是最好的。从JScrollPane和JList自动滚动中找到
为面板添加/删除组件时,应在面板上调用revalidate()以确保组件布局正确。
然后,如果你想滚动到底部,那么你应该能够使用:
JScrollBar sb = scrollPane.getVerticalScrollBar();
sb.setValue( sb.getMaximum() );
这就是我自动向上或向下滚动的方式:
/**
* Scrolls a {@code scrollPane} all the way up or down.
*
* @param scrollPane the scrollPane that we want to scroll up or down
* @param direction we scroll up if this is {@link ScrollDirection#UP},
* or down if it's {@link ScrollDirection#DOWN}
*/
public static void scroll(JScrollPane scrollPane, ScrollDirection direction) {
JScrollBar verticalBar = scrollPane.getVerticalScrollBar();
// If we want to scroll to the top, set this value to the minimum,
// else to the maximum
int topOrBottom = direction == ScrollDirection.UP ?
verticalBar.getMinimum() :
verticalBar.getMaximum();
AdjustmentListener scroller = new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
Adjustable adjustable = e.getAdjustable();
adjustable.setValue(topOrBottom);
// We have to remove the listener, otherwise the
// user would be unable to scroll afterwards
verticalBar.removeAdjustmentListener(this);
}
};
verticalBar.addAdjustmentListener(scroller);
}
public enum ScrollDirection {
UP, DOWN
}