Swing: Scroll to bottom of JScrollPane, conditional on current viewport location

∥☆過路亽.° 提交于 2019-11-30 12:57:15

Take a look at the scrollRectToVisible(Rectangle r) and modelToView(int pos)

That should get you what you're looking for without disturbing the user's selection.

As for the scrollbar, try forcing the scroll and the append into occur on different events. For example:

if (atBottom) {
    // append new line & do scroll
    SwingUtilities.invokerLater(new Runnable(){
        public void run() {
            // append text
        }});
} else {
    // append newline
    // append text
}
Emil

Based on previous answers and further Google'ing I made a test in which a Thread continously appends Strings to a JTextArea in a JScrollPane. I think it is important to use invokeLater here, since the JScrollBar needs to be updated with its new maximum value before we scroll to that value. Using invokeLater, the AWT Thread will take care of this.

private class AppendThread extends Thread {
    public void run() {
      while (true) {
        String s = "random number = " + Math.random() + "\n";
        boolean scrollDown = textAreaBottomIsVisible();
        textArea.append(s);
        if (scrollDown) {
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                      JScrollBar bar = scrollPane.getVerticalScrollBar();
                      bar.setValue(bar.getMaximum());
                  }
              }
          );
        }
        try {
          Thread.sleep(1000);
        } catch (Exception e) {
          System.err.println("exception = " + e);
        }
      }
    }

    private boolean textAreaBottomIsVisible() {
      Adjustable sb = scrollPane.getVerticalScrollBar();
      int val = sb.getValue();
      int lowest = val + sb.getVisibleAmount();
      int maxVal = sb.getMaximum();
      boolean atBottom = maxVal == lowest;
      return atBottom;
    }
}

Check out this example.

Although, I would change the code to use the following which is more efficient:

caret.setDot(textArea.getDocument().getLength());

I've spent the last few days trying different approaches to this exact problem. The best solution I've found is to replace the layout manager of JScrollPane's viewport and implement all the desired scrolling behavior there. The jumpy scrollbar knob is gone, and it's blazing fast -- so fast that it created another race condition I had to work around. Details are here: http://www.java-forums.org/awt-swing/56808-scroll-bar-knob-jumpy-when-component-growing.html

A little late but here is something i found: http://www.camick.com/java/source/SmartScroller.java

In essence you can use following code:

JScrollPane scrollPane = new JScrollPane(myOversizedComponent);
// Injects smartscroll behaviour to your scrollpane
new SmartScroller(scrollPane); 

And here the SmartScroller class:

import java.awt.Component;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

/**
 *  The SmartScroller will attempt to keep the viewport positioned based on
 *  the users interaction with the scrollbar. The normal behaviour is to keep
 *  the viewport positioned to see new data as it is dynamically added.
 *
 *  Assuming vertical scrolling and data is added to the bottom:
 *
 *  - when the viewport is at the bottom and new data is added,
 *    then automatically scroll the viewport to the bottom
 *  - when the viewport is not at the bottom and new data is added,
 *    then do nothing with the viewport
 *
 *  Assuming vertical scrolling and data is added to the top:
 *
 *  - when the viewport is at the top and new data is added,
 *    then do nothing with the viewport
 *  - when the viewport is not at the top and new data is added, then adjust
 *    the viewport to the relative position it was at before the data was added
 *
 *  Similiar logic would apply for horizontal scrolling.
 */
public class SmartScroller implements AdjustmentListener
{
    public final static int HORIZONTAL = 0;
    public final static int VERTICAL = 1;

    public final static int START = 0;
    public final static int END = 1;

    private int viewportPosition;

    private JScrollBar scrollBar;
    private boolean adjustScrollBar = true;

    private int previousValue = -1;
    private int previousMaximum = -1;

    /**
     *  Convenience constructor.
     *  Scroll direction is VERTICAL and viewport position is at the END.
     *
     *  @param scrollPane the scroll pane to monitor
     */
    public SmartScroller(JScrollPane scrollPane)
    {
        this(scrollPane, VERTICAL, END);
    }

    /**
     *  Convenience constructor.
     *  Scroll direction is VERTICAL.
     *
     *  @param scrollPane the scroll pane to monitor
     *  @param viewportPosition valid values are START and END
     */
    public SmartScroller(JScrollPane scrollPane, int viewportPosition)
    {
        this(scrollPane, VERTICAL, viewportPosition);
    }

    /**
     *  Specify how the SmartScroller will function.
     *
     *  @param scrollPane the scroll pane to monitor
     *  @param scrollDirection indicates which JScrollBar to monitor.
     *                         Valid values are HORIZONTAL and VERTICAL.
     *  @param viewportPosition indicates where the viewport will normally be
     *                          positioned as data is added.
     *                          Valid values are START and END
     */
    public SmartScroller(JScrollPane scrollPane, int scrollDirection, int viewportPosition)
    {
        if (scrollDirection != HORIZONTAL
        &&  scrollDirection != VERTICAL)
            throw new IllegalArgumentException("invalid scroll direction specified");

        if (viewportPosition != START
        &&  viewportPosition != END)
            throw new IllegalArgumentException("invalid viewport position specified");

        this.viewportPosition = viewportPosition;

        if (scrollDirection == HORIZONTAL)
            scrollBar = scrollPane.getHorizontalScrollBar();
        else
            scrollBar = scrollPane.getVerticalScrollBar();

        scrollBar.addAdjustmentListener( this );

        //  Turn off automatic scrolling for text components

        Component view = scrollPane.getViewport().getView();

        if (view instanceof JTextComponent)
        {
            JTextComponent textComponent = (JTextComponent)view;
            DefaultCaret caret = (DefaultCaret)textComponent.getCaret();
            caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
        }
    }

    @Override
    public void adjustmentValueChanged(final AdjustmentEvent e)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                checkScrollBar(e);
            }
        });
    }

    /*
     *  Analyze every adjustment event to determine when the viewport
     *  needs to be repositioned.
     */
    private void checkScrollBar(AdjustmentEvent e)
    {
        //  The scroll bar listModel contains information needed to determine
        //  whether the viewport should be repositioned or not.

        JScrollBar scrollBar = (JScrollBar)e.getSource();
        BoundedRangeModel listModel = scrollBar.getModel();
        int value = listModel.getValue();
        int extent = listModel.getExtent();
        int maximum = listModel.getMaximum();

        boolean valueChanged = previousValue != value;
        boolean maximumChanged = previousMaximum != maximum;

        //  Check if the user has manually repositioned the scrollbar

        if (valueChanged && !maximumChanged)
        {
            if (viewportPosition == START)
                adjustScrollBar = value != 0;
            else
                adjustScrollBar = value + extent >= maximum;
        }

        //  Reset the "value" so we can reposition the viewport and
        //  distinguish between a user scroll and a program scroll.
        //  (ie. valueChanged will be false on a program scroll)

        if (adjustScrollBar && viewportPosition == END)
        {
            //  Scroll the viewport to the end.
            scrollBar.removeAdjustmentListener( this );
            value = maximum - extent;
            scrollBar.setValue( value );
            scrollBar.addAdjustmentListener( this );
        }

        if (adjustScrollBar && viewportPosition == START)
        {
            //  Keep the viewport at the same relative viewportPosition
            scrollBar.removeAdjustmentListener( this );
            value = value + maximum - previousMaximum;
            scrollBar.setValue( value );
            scrollBar.addAdjustmentListener( this );
        }

        previousValue = value;
        previousMaximum = maximum;
    }
}
Stephane Grenier
public static void scrollToBottom(JComponent component) 
{
    Rectangle visibleRect = component.getVisibleRect();
    visibleRect.y = component.getHeight() - visibleRect.height;
    component.scrollRectToVisible(visibleRect);
}

You can find the full details here: How to make JTextPane autoscroll only when scroll bar is at bottom and scroll lock is off?

Narain
DefaultCaret caret = (DefaultCaret)textArea.getCaret();  
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!