Java / Swing : JTextArea in a JScrollPane, how to prevent auto-scroll?

前端 未结 3 1744
南旧
南旧 2020-11-30 10:42

here\'s a runnable piece of code that shows what my \"problem\" is.

I\'ve got a JTextArea wrapped in a JScrollPane. When I change the text

相关标签:
3条回答
  • 2020-11-30 11:00

    How to set AUTO-SCROLLING of JTextArea in Java GUI?

    http://download.oracle.com/javase/1.5.0/docs/api/javax/swing/text/DefaultCaret.html#NEVER_UPDATE

    Try:

    JTextArea textArea = new JTextArea();
    DefaultCaret caret = (DefaultCaret)textArea.getCaret();
    caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
    

    This should prevent the caret from automatically making the document scroll to the bottom.

    0 讨论(0)
  • 2020-11-30 11:08

    Answering my own question: I'm not exactly sure this is the best way to solve my issue, but setting the JTextArea's caret using setCaretPosition(0) seems to work fine:

    jta.setText( sb.toString() );
    jta.jta.setCaretPosition( 0 );
    
    0 讨论(0)
  • 2020-11-30 11:13

    You have run into a very strange behaviour in the implementation of the Document classes. I use a DefaultStyledDocument in a JTextPane inside a JScrollPane.

    Now, here is the wierd thing. If I update the document on the EventQueue (like you do by scheduling a runnable to run later) the scroll pane automatically scrolls to the end.

    However, the document classes claim to be thread safe and actually updatable from another thread. If I make sure to update on another thread than the EventQueue everything works fine but the scroll pane does NOT scroll to the end.

    I have no explanation as to why this is so, I haven't looked in the Swing source. I have been exploiting this "feature" since 2006 and it has been consistent so far :-)

    0 讨论(0)
提交回复
热议问题