Making a JScrollPane automatically scroll all the way down

后端 未结 6 1365
夕颜
夕颜 2021-02-05 07:42

I am trying to implement a JScrollPane with a JTextArea. The JTextArea is being appended to, and I want the JScrollPane to keep scrolling down as more text is added. How can thi

6条回答
  •  死守一世寂寞
    2021-02-05 07:56

    The accepted solution works good, but only when the text area is editable, i.e. without jTextArea.setEditable(false) . The solution suggested by Krigath is more general, but has the problem as asked here JScrollPane and JList auto scroll. Using answers from that question you can get general solution, e.g.:

            JScrollPane scrollPane = new JScrollPane(jTextArea);
    
        verticalScrollBarMaximumValue = scrollPane.getVerticalScrollBar().getMaximum();
        scrollPane.getVerticalScrollBar().addAdjustmentListener(
                e -> {
                    if ((verticalScrollBarMaximumValue - e.getAdjustable().getMaximum()) == 0)
                        return;
                    e.getAdjustable().setValue(e.getAdjustable().getMaximum());
                    verticalScrollBarMaximumValue = scrollPane.getVerticalScrollBar().getMaximum();
                });
    

    The Pane then is scrolled down only when vertical scroll bar is expanding, in response to appended lines of text.

    I admit that that a method to filter events without extra variables could be found, and would appreciate if somebody post it.

提交回复
热议问题