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:
scrollPane.getViewport().setViewPosition(new Point(0,0));
but how do I scroll exactly to the very bottom? (Too far and it jitters)
A JScrollBar is a component and it doesn't handle its own events whereas a JScrollPane is a Container and it handles its own events and performs its own scrolling.
Just use the reference to your JScrollPane object, get the vertical scroll bar from it using getVerticalScrollBar , and then call setUnitIncrement on it, like this: myJScrollPane. getVerticalScrollBar(). setUnitIncrement(16);
getContentPane(). add(scrollPanel); This code will work in general to add JScrollPane to JPanel. Adjust bounds of frame, panel and scrollpane according to your requirements but ensure that the bounds of JScrollPane are within the bounds of the frame otherwise the scrollpane will not be visible.
JScrollBar vertical = scrollPane.getVerticalScrollBar(); vertical.setValue( vertical.getMaximum() );
After many hours of attempting to find an answer other than one using the scrollRectToVisible() method, I've succeeded. I've found that if you use the following code after you output text to the text area in the scrollpane, it will automatically focus on the bottom of the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
So, at least for me, my print method looks like this
public void printMessage(String message) { textArea.append(message + endL); textArea.setCaretPosition(textArea.getDocument().getLength()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With