I have a Java application with a scrollable text pane (JScrollPane). What I want to do is update the relevant code so that whenever a line of text is added, the pane automatically scrolls down to display the line.
I’ve been going throught the Swing library documentation looking for applicable member functions, and I’m getting lost in a TMI way. Any Java jocks willing to point me in the right direction?
javax.swing.JComponent scrollRectToVisible( Rectangle ) called on the JComponent that is inside the scroll pane is what you want.
If the object is a list or a table, you can find that rectangle by “getCellBounds”. If the object is a text pane, you’ve got to find the right local component coordinates somehow. I’d try a font metric object to figure out the size of the lines, and use that.
Hope that helps.
Here’s a different approach I have used, tweaking the scroll bar. This code snippet assumes you have a reference to the thing being scrolled.
// Now scroll to bottom
Container parent = mypanel.getParent();
if(parent instanceof JViewport) {
JViewport vp = (JViewport)parent;
parent = vp.getParent();
if(parent instanceof JScrollPane) {
JScrollPane scrollPane = (JScrollPane)parent;
JScrollBar sb = scrollPane.getVerticalScrollBar();
if(sb != null) {
sb.setValue(sb.getMaximum());
}
}
}
In addition to this, if you are scrolling text, you might want to call JTextComponent.setCaretPosition(length - 1) to put the caret at the very bottom.