为什么我的Java Swing JScrollPane一直滚动到顶部



我正在开发一个小型计算器小部件,用于保存计算日志。它应该在每次添加新条目时滚动到日志的底部。这部分似乎运行良好。问题是,当我按下一个不添加到日志中的计算器按钮时,日志窗格总是滚动回顶部,滚动条就会消失。我怎样才能阻止它这样做?

添加到日志中的代码是:

    private JTextPane logArea; //This is placed inside a JScrollPane
    private void log(String m, SimpleAttributeSet a) {
       int len = logArea.getDocument().getLength();
       logArea.setEditable(true);
       logArea.setCaretPosition(len);
       logArea.setCharacterAttributes(a, false);
       logArea.replaceSelection(m);
       logArea.scrollRectToVisible(new Rectangle(0,logArea.getBounds(null).height,1,1));
       logArea.setEditable(false);
   }

似乎扰乱了滚动的代码是:

  private void addDigit(char digit) {
       if (clearDisplayBeforeDigit) {
          clearNumDisplay();
       }
       if (numInDisplay.getText().length() < maxNumDigits) {
          if (digit == '.') { //Point
             if (!hasPoint) { //Only one point allowed
                hasPoint = true;
                String newText = numInDisplay.getText() + ".";
                numInDisplay.setText(newText);
             }
          } else { //New digit
             String newText = numInDisplay.getText() + digit;
             numInDisplay.setText(newText);
          }
       }
    }

您认为导致问题的代码甚至没有引用logArea,那么您为什么认为这会导致问题呢?

您不需要使用scrollRectToVisible(…)方法。setCaretPosition(…)应该能起作用。尽管您应该获得文档的长度,并在更新文档后调用该方法。

查看文本区域滚动以了解更多信息。

编辑:

我也不认为有任何理由更改文本区域的可编辑性。

最新更新