[英]How to detect when a Java Swing scroll bar is at or near the bottom of the bar?
[英]How to auto scroll to bottom in Java Swing
我有一個帶有JScrollPane(根據需要有垂直滾動條)的簡單JPanel。
事情被添加到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自動滾動找到
這就是我自動向上或向下滾動的方式:
/**
* 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
}
為面板添加/刪除組件時,應調用面板上的revalidate()以確保組件正確布局。
然后,如果你想滾動到底部,那么你應該可以使用:
JScrollBar sb = scrollPane.getVerticalScrollBar();
sb.setValue( sb.getMaximum() );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.