Leonide
Leonide

Reputation: 245

Why does my Java Swing JScrollPane keep scrolling to the top?

I'm developing a small calculator widget that keeps a running log of calculations. It's supposed to scroll to the bottom of the log every time a new entry is added. This part seems to be working fine. The problem is, when I press a calculator button that does not add to the log, the log pane always scrolls back to the top, and the scrollbar disappears. How can I keep it from doing this?

The code that adds to the log is:

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

The code that seems to be messing with the scroll is:

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

Upvotes: 2

Views: 839

Answers (1)

camickr
camickr

Reputation: 324118

The code you think is causing the problem doesn't even reference the logArea, so why would you think this causes the problem?

You don't need to use the scrollRectToVisible(...) method. The setCaretPosition(...) should do the trick. Although you should get the length of the document and invoke that method AFTER you update the document.

Check out Text Area Scrolling for more information.

Edit:

I also don't see any reason for changing the editability of the text area.

Upvotes: 3

Related Questions