2011-06-16 16 views
4

我有一個帶JScrollPane(根據需要帶有垂直滾動條)的簡單JPanel。事物被添加到(或從JPanel中移除),當它超出面板的底部時,我想讓JScrollPane根據需要自動向下滾動到底部,或者在面板上有部分組件離開時向上滾動。我該怎麼做?我猜我需要某種類型的監聽程序,只要JPanel高度發生變化就會被調用?還是有像JScrollPanel.setutoScroll(true)這樣簡單的東西?如何在Java swing中自動滾動到底部

回答

5

當您爲面板添加/刪除組件時,應在面板上調用revalidate()以確保組件佈置正確。

然後,如果你想滾動至底部,那麼你應該能夠使用:

JScrollBar sb = scrollPane.getVerticalScrollBar(); 
sb.setValue(sb.getMaximum()); 
11
scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() { 
     public void adjustmentValueChanged(AdjustmentEvent e) { 
      e.getAdjustable().setValue(e.getAdjustable().getMaximum()); 
     } 
    }); 

這將是最好的。從JScrollPane and JList auto scroll

+0

這個唯一的問題是,你不能手動調節滾動條。 – ComputerEngineer88 2017-10-17 14:18:14

1

發現這個是我向上或向下滾動自動一路:

/** 
* 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.equals(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 since otherwise the user would be unable to scroll afterwards 
      verticalBar.removeAdjustmentListener(this); 
     } 
    }; 
    verticalBar.addAdjustmentListener(scroller); 
} 

public enum ScrollDirection { 
    UP, DOWN 
}