简体   繁体   中英

Java disable horizontal autoscroll in JTextArea

I use a Console for showing errors and status messages in my application. I can show and hide it using a checkbox, which is working pretty well. My problem now is that some lines can be pretty long (for example, if an Exception is thrown) and if it is the last line the Caret is at the very right position.

I want to disable autoscrolling in the horizontal direction, but keep it in the vertical. Also I do NOT want to remove the scrollbar and use linewrapping. I just want to get rid of my Console always being scrolled to the right.

I already tried setting the Caret position myself, but I was not able to really figure out where I should do so. My last attempt was leading into a crash when marking text, because I put the code into the caretUpdate method, which seems to be the wrong place.

//Prevent horizontal autoscroll
textArea.addCaretListener(new CaretListener() {
  @Override
  public void caretUpdate(CaretEvent e) {
    try {
      textArea.setCaretPosition(textArea.getLineStartOffset(textArea.getLineCount() - 1));
    } catch (BadLocationException e1) {
    e1.printStackTrace();
    }
  }
});

Okay actually I found out that it didn't work, because the Caret is also set in my Console class and thus overwritten.

For all who are interested, this seems like a good aproach to me:

    textArea.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            try {
                textArea.setCaretPosition(
                   textArea.getLineStartOffset(textArea.getLineCount() - 1)
                );
            } catch (BadLocationException e1) {
                e1.printStackTrace();
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM