Search code examples
javajscrollpanejtextareaautoscroll

Java JScrollPane toggle autoscroll on/off


I got a JtextArea in a JScrollPane and want to switch between AutoScroll on/off.

EDIT: AutoScroll - permanent scrolled down to the Bottom when JTextArea becomes extended

For Autoscroll i use:

DefaultCaret caret = (DefaultCaret)textPane.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

Which works fine. As switch i use a Checkbox:

    JCheckBox chckbxNewCheckBox = new JCheckBox("AutoScroll");
    chckbxNewCheckBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if(chckbxNewCheckBox.isSelected()){
                caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
            } else {
                caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
            }
        }
    });

With this Method i am able to switch from the default "on" to "off". But switching "on" again does not work. The JtextArea is not editable.

Thanks =)


Solution

  • Try the following:

    textArea.setCaretPosition(textArea.getDocument().getLength());
    caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    

    Another option might be to use Smart Scrolling which allows the user to control scrolling by positioning the scrollbar.