How to auto scroll down JTextArea after append?

前端 未结 2 1890
予麋鹿
予麋鹿 2021-01-12 02:13

I\'ve created a JFrame, with a JTextArea. I would like to scroll down the textarea automatically, after each append. How should I manage it?

I\'ve tried log.se

相关标签:
2条回答
  • 2021-01-12 02:24

    Mine is a little simpler and efficient. We set the caret to the length of the text to put it at the end like so.

    public void appendText(String str){
        txtArea.append(str + "\n");
        scrollDown();
    }
    
    public void scrollDown(){
        txtArea.setCaretPosition(txtArea.getText().length());
    }
    
    0 讨论(0)
  • 2021-01-12 02:46

    there are two ways (but JTextArea must be placed in JScrollPane)

    a) set Caret (correct of ways)

    e.g.

      DefaultCaret caret = (DefaultCaret) log.getCaret();
      caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    

    b) moving with JScrollBar (from JScrollPane) to its max value

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