简体   繁体   English

Java在JTextArea中禁用水平自动滚动

[英]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. 我现在的问题是,某些行可能会很长(例如,如果引发Exception),并且如果这是最后一行,则插入号位于正确的位置。

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. 我最后一次尝试在标记文本时导致崩溃,因为我将代码放入了caretUpdate方法中,这似乎是错误的位置。

//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. 好的,实际上我发现它不起作用,因为Caret也在我的Console类中设置,因此被覆盖了。

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();
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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