JTextPane或JTextPane设置了滚动条,文本增加后,滚动条自动下滑,追加文本的例子

http://zhizaibide1987.iteye.com/blog/1012955

 https://zhidao.baidu.com/question/2116908942184706107.html

JTextPane或JTextPane设置了滚动条,文本增加后,滚动条自动下滑

例如:日志打印窗口,日志增加后,滚动条自动下滑,显示最新的日志。

实现方法:将光标移动到文本的最后。

JTextArea的实现:

Java代码   收藏代码
  1. //实现垂直滚动条自动下滑到最低端  
  2. logTxtArea.setCaretPosition(logTxtArea.getText().length());  

JTextPane的实现:

Java代码   收藏代码
  1. //实现垂直滚动条自动下滑到最低端  
  2. msgShowTxtPane.setCaretPosition(msgShowTxtPane.getStyledDocument().getLength());  

java的JtextPane没有append方法,可以使用Document来添加文本,例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
   //设置字体大小
         SimpleAttributeSet attrset =  new  SimpleAttributeSet();
         StyleConstants.setFontSize(attrset, 24 );
          
         //插入内容
         JTextPane textPane =  new  JTextPane();
         Document docs = textPane.getDocument(); //获得文本对象
         try  {
             docs.insertString(docs.getLength(),  "要插入的内容" , attrset); //对文本进行追加
         catch  (BadLocationException e) {
             e.printStackTrace();
         }

猜你喜欢

转载自www.cnblogs.com/donaldlee2008/p/9137880.html
今日推荐