Swing中怎樣使JScrollPane中滾動條始終在最下面


最近用swing寫了一個簡單的聊天界面,但是頁面上的JScrollPane一直移動在最上面,下面是解決怎么讓JScrollPane移動到最后一行的幾種方法:

1. 利用JTextArea的selectAll();方法在添加信息之后強制將光標移動到最后一行。據說是Aviva中采用的方式。
2.使用JTextArea的setCaretPosition();手動設置光標的位置為最后一行。人氣頗高。使用方法也很簡單,如下:textArea.setCaretPosition(textArea.getDocument().getLength());
3.(copy的)在JTextArea加載了自動滾動條JScroll之后,將JTextArea加入到JScrolPanel的ViewPort中: (有一些Bug,使得圖像有點閃爍) 
     recvScrollPane.getViewport().add(recvArea, null);
     然后在JTextArea插入最后一條新消息之后,將滾動條的Viewport重新設置到最底端的位置:
     int height = 20;
     Point p = new Point();
     p.setLocation(0, recvArea.getLineCount() * height);
     recvScrollPane.getViewport().setViewPosition(p);
4.網上以為仁兄用英文說的tricky treatment
JTextPane pane = new JTextPane();... // add some text to the JTextPane...
    Document doc = pane.getDocument();
   pane.select(doc.getLength(), doc.getLength()); // this should enforce the viewport move to where the line being selected.
   ...
5.這似乎是最常用的方法,但是實際使用情況是只能到倒數第二行。
JScrollBar   sbar=spContainer.getVerticalScrollBar();   
sbar.setValue(sbar.getMaximum());


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM