I need to scroll a JScrollPane to the bottom. The JScrollPane contains a JPanel, which contains a number of JLabel\'s.
To scroll to the top, I just do:
I adapted the code of Peter Saitz. This version leaves the scrollbar working after it has finished scrolling down.
private void scrollToBottom(JScrollPane scrollPane) {
JScrollBar verticalBar = scrollPane.getVerticalScrollBar();
AdjustmentListener downScroller = new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
Adjustable adjustable = e.getAdjustable();
adjustable.setValue(adjustable.getMaximum());
verticalBar.removeAdjustmentListener(this);
}
};
verticalBar.addAdjustmentListener(downScroller);
}
I have tried several method. Some use bar.setValue(bar.getMaximum())
, but the maximum is always 100 while the range of bar will be much more than 100. Some use textArea, but it is not suitable for that there is only a JTable in the JScrollPane. And I thing about a method, maybe stupid but effective.
JScrollBar bar=jsp.getVerticalScrollBar();
int x=bar.getValue();
for(int i=100;i<2000000000;i+=100)
{
bar.setValue(i);
if(x==bar.getValue())
break;
x=bar.getValue();
}
If your JScrollPane only contains a JTextArea then:
JScrollPane.getViewport().setViewPosition(new Point(0,JTextArea.getDocument().getLength()));
ScrollBar vertical = scrollPane.getVerticalScrollBar();
vertical.setValue( vertical.getMaximum() - 1 );
just set value to: vertical.getMaximum() - 1
scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
e.getAdjustable().setValue(e.getAdjustable().getMaximum());
}
});
None of the answers worked for me. For some reason my JScrollPane
was not scrolling to the very bottom, even if I revalidated everything.
This is what worked for me:
SwingUtilities.invokeLater(() -> {
JScrollBar bar = scroll.getVerticalScrollBar();
bar.setValue(bar.getMaximum());
});