JScrollPane 在末尾追加文本,并更新卷滚条,使新添文本可视

 

//jtp是JTextPane的变量名

//每秒钟向jtp追加一条当前时间字符串文本

Timer t = new Timer(1000, new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent evt) {
             try {
                 String timeString = fmt. format (new Date());

                //将插入光标定位到jtp末尾

                 jtp.setCaretPosition(jtp.getDocument().getLength());

                 //插入字符串

                 jtp.replaceSelection(timeString+"\n");

                 //为使其卷滚可见,计算坐标

                 Rectangle r = jtp.modelToView(jtp.getDocument().getLength());

                 //注意:这里需要判断是否为null,因为如果jtp还未绘制的话会返回null

                 if (r != null) {

                     //卷滚可见

                     jtp.scrollRectToVisible(r);
                 }   } catch (BadLocationException ex) {
                 Logger.getLogger(eeee.class.getName()).log(Level.SEVERE, null, ex);
             }
         }

         SimpleDateFormat fmt =
            new SimpleDateFormat("HH:mm:ss");
         });
         t.start();

你可能感兴趣的:(swing,JScrollPane,jtextpane)