2

I would like to scroll down a JScrollPane automatically when updating him. My JScrollPane contains some panels that I had time to time according to user actions.

Tests made

Existing solutions are all about JTextArea or JList. The solution below works but has the problem to override every user actions (If we manually click on the ScrollBox, it will scroll down automatically after) :

@Override
public void adjustmentValueChanged(AdjustmentEvent e){
    e.getAdjustable().setValue(e.getAdjustable().getMaximum()); 
}

I have tried this solution :

private void addPanel(JPanel newPanel){
     scrollPanel.add(newPanel);
     scrollDown(); 
}

private void scrollDown(){
    JScrollBar vertical = scroll.getVerticalScrollBar();
    vertical.setValue(vertical.getMaximum());
}

I call it just after adding a JPanel to my JScrollPane. But it scrolls not to the exact bottom but just before which is not very... clean.

Community
  • 1
  • 1
Kapcash
  • 6,377
  • 2
  • 18
  • 40

1 Answers1

3

After trying to see why my second solution doesn't work completly, I printed the value (high) of the scroll bar, to see when it is updated with scrollPane.getVerticalScrollBar().getValue();

This value updates itself not immediatly after adding the JPanel, but at the next addPanel() call (so with an offset).

I simply had to call the revalidate() method on my entire window / frame to make this work.

private void scrollDown(){
    window.revalidate(); //Update the scrollbar size
    JScrollBar vertical = scroll.getVerticalScrollBar();
    vertical.setValue(vertical.getMaximum());
}

Note : If you revalidate only the JScrollPane, it doesn't work.

Kapcash
  • 6,377
  • 2
  • 18
  • 40