JScrollPane scroll at last added line
I have JTextArea text and JScrollPane pane=new JScrollPane(text), I put pane.setAutoScrolls(true). How开发者_StackOverflow社区 to get that when I append some text to my component text that pane scrolls at the end ( last line ) ?
follows link from this thread ScrollPane scroll to bottom problem
Best (and up-to-date, as far as I can tell) explanation of how caret is moved, by Rob Camick:
http://tips4java.wordpress.com/2008/10/22/text-area-scrolling/
Is it possible, that you are not on the EDT? If the append does not happen on the EDT, the position of the JTextArea does not update.
Short, runnable example to show this behaviour:
import java.awt.TextArea;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class Sample {
public static void main(String[] args) {
/*
* Not on EDT
*/
showAndFillTextArea("Not on EDT", 0, 0);
/*
* On EDT
*/
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
showAndFillTextArea("On EDT", 400, 0);
}
});
}
private static void showAndFillTextArea(String title, int x, int y) {
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollPane = new JScrollPane(textArea);
frame.getContentPane().add(scrollPane);
frame.pack();
frame.setLocation(x, y);
frame.setVisible(true);
for(int i = 0; i < 50; i++) {
textArea.append("Line" + i + "\n");
}
}
}
精彩评论