保持 JTextArea 滚动位置 [英] Maintaing JTextArea scroll position

查看:37
本文介绍了保持 JTextArea 滚动位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JScrollPane,其中 JTextArea 设置为其视口.

I have a JScrollPane with a JTextArea set as its view port.

我大约每秒持续更新一次 JTextArea 上显示的(多行)文本.每次文本更新时,JScrollPane 都会一直移动到文本底部.

I update the (multi line) text shown on the JTextArea continously about once a second. Each time the text updates, JScrollPane goes all the way to the bottom of the text.

相反,我想找出当前显示为原始文本第一行的行号,并使该行成为文本更新时显示的第一行(或者如果新文本没有没有那么多行,然后一直滚动到底部).

Instead, I'd like to figure out the line number that is currently shown as the first line in the original text, and have that line be the first line shown when the text has been updated (or if the new text doesn't have that many lines, then scroll all the way to the bottom).

我第一次尝试这样做是获取当前插入符号位置,根据该位置计算行,然后设置文本区域以显示该行:

My first attempt of doing this was to get the current caret position, figure the line based on that, and then set the text area to show that line:

    int currentPos = textArea.getCaretPosition();
    int currentLine = 0;
    try {
        for(int i = 0; i < textArea.getLineCount(); i++) {
            if((currentPos >= textArea.getLineStartOffset(i)) && (currentPos < gameStateTextArea.getLineEndOffset(i))) {
                currentLine = i;
                break;
            }
        }
    } catch(Exception e) { }

    textArea.setText(text);

    int newLine = Math.min(currentLine, textArea.getLineCount());
    int newOffset = 0;
    try {
        newOffset = textArea.getLineStartOffset(newLine);
    } catch(Exception e) { }

    textArea.setCaretPosition(newOffset);

这几乎可以满足我的需求,但需要用户在文本区域内单击以更改插入符号位置,以便滚动保持状态(这不太好).

This was almost acceptable for my needs, but requires the user to click inside the text area to change the caret position, so that the scrolling will maintain state (which isn't nice).

我将如何使用(垂直)滚动位置来执行此操作?

How would I do this using the (vertical) scroll position instead ?

推荐答案

这是从 API 文档拼凑起来的,未经测试:

This is pieced together, untested, from the API documentation:

  • 在您的 JScrollPane 上使用 getViewport() 来获取视口.
  • 使用 Viewport.getViewPosition() 获取左上角坐标.这些是绝对值,而不是滚动文本的百分比.
  • 使用 Viewport.addChangeListener() 在左上角位置发生变化时得到通知(除其他外).当然,您可能希望创建一种机制来区分用户的更改和您的程序所做的更改.
  • 使用 Viewport.setViewPosition() 将左上角位置设置为干扰前的位置.
  • use getViewport() on your JScrollPane to get a hold of the viewport.
  • use Viewport.getViewPosition() to get the top-left coordinates. These are absolute, not a percentage of scrolled text.
  • use Viewport.addChangeListener() to be notified when the top-left position changes (among other things). You may want to create a mechanism to distinguish user changes from changes your program makes, of course.
  • use Viewport.setViewPosition() to set the top-left position to where it was before the disturbance.

更新:

  • 要阻止 JTextArea 滚动,您可能需要覆盖其 getScrollableTracksViewport{Height|Width}() 方法以返回 false.
  • To stop JTextArea from scrolling, you may want to override its getScrollableTracksViewport{Height|Width}() methods to return false.

更新 2:

以下代码执行您想要的操作.令人惊讶的是,为了让它工作,我必须经历多少麻烦:

The following code does what you want. It's amazing how much trouble I had to go to to get it to work:

  • 显然 setViewPosition 必须使用 invokeLater 推迟,因为如果它过早完成,文本更新将在它之后出现并使其效果无效.
  • 此外,由于某些可能与并发有关的奇怪原因,我必须在其构造函数中将正确的值传递给我的 Runnable 类.我一直在使用 orig 的全局"实例,并且一直将我的位置设置为 0,0.
  • apparently the setViewPosition has to be postponed using invokeLater because if it's done too early the text update will come after it and nullify its effect.
  • also, for some weird reason perhaps having to do with concurrency, I had to pass the correct value to my Runnable class in its constructor. I had been using the "global" instance of orig and that kept setting my position to 0,0.
public class Sami extends JFrame implements ActionListener {

   public static void main(String[] args) {
      (new Sami()).setVisible(true);
   }

   private JTextArea textArea;
   private JScrollPane scrollPane;
   private JButton moreTextButton = new JButton("More text!");
   private StringBuffer text = new StringBuffer("0 Silly random text.\n");
   private Point orig = new Point(0, 0);

   public Sami() {
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      getContentPane().setLayout(new BorderLayout());
      this.textArea = new JTextArea() {
         @Override
         public boolean getScrollableTracksViewportHeight() {
            return false;
         }
         @Override
         public boolean getScrollableTracksViewportWidth() {
            return false;
         }
      };
      this.scrollPane = new JScrollPane(this.textArea);
      getContentPane().add(this.scrollPane, BorderLayout.CENTER);
      this.moreTextButton.addActionListener(this);
      getContentPane().add(this.moreTextButton, BorderLayout.SOUTH);
      setSize(400, 300);
   }

   @Override
   public void actionPerformed(ActionEvent arg0) {
      int lineCount = this.text.toString().split("[\\r\\n]").length;
      this.text.append(lineCount + "The quick brown fox jumped over the lazy dog.\n");
      Point orig = this.scrollPane.getViewport().getViewPosition();
      // System.out.println("Orig: " + orig);
      this.textArea.setText(text.toString());
      SwingUtilities.invokeLater(new LaterUpdater(orig));
   }

   class LaterUpdater implements Runnable {
      private Point o;
      public LaterUpdater(Point o) {
         this.o = o;
      }
      public void run() {
         // System.out.println("Set to: " + o);
         Sami.this.scrollPane.getViewport().setViewPosition(o);
      }
   } 

}

这篇关于保持 JTextArea 滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆