zoukankan      html  css  js  c++  java
  • 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());

  • 相关阅读:
    Leetcode 50.Pow(x,n) By Python
    Leetcode 347.前K个高频元素 By Python
    Leetcode 414.Fizz Buzz By Python
    Leetcode 237.删除链表中的节点 By Python
    Leetcode 20.有效的括号 By Python
    Leetcode 70.爬楼梯 By Python
    Leetcode 190.颠倒二进制位 By Python
    团体程序设计天梯赛 L1-034. 点赞
    Wannafly挑战赛9 C-列一列
    TZOJ Start
  • 原文地址:https://www.cnblogs.com/tooker/p/4695681.html
Copyright © 2011-2022 走看看