Java Swing How to - Make JScrollPane scroll to follow input focus








Question

We would like to know how to make JScrollPane scroll to follow input focus.

Answer

import java.awt.KeyboardFocusManager;
import java.awt.Rectangle;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/* w w  w  .  j  a  va2  s.  c  o  m*/
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JViewport;

public class Main {
  public static void main(String[] args) {
    int ROWS = 100;
    JPanel content = new JPanel();
    content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
    content.add(new JLabel("Thanks for helping out. Use tab to move around."));
    for (int i = 0; i < ROWS; i++) {
      JTextField field = new JTextField("" + i);
      field.setName("field#" + i);
      content.add(field);
    }
    KeyboardFocusManager.getCurrentKeyboardFocusManager()
        .addPropertyChangeListener("focusOwner", new PropertyChangeListener() {
          @Override
          public void propertyChange(PropertyChangeEvent evt) {
            if (!(evt.getNewValue() instanceof JComponent)) {
              return;
            }
            JViewport viewport = (JViewport) content.getParent();
            JComponent focused = (JComponent) evt.getNewValue();
            if (content.isAncestorOf(focused)) {
              Rectangle rect = focused.getBounds();
              Rectangle r2 = viewport.getVisibleRect();
              content.scrollRectToVisible(new Rectangle(rect.x, rect.y,
                  (int) r2.getWidth(), (int) r2.getHeight()));
            }
          }
        });
    JFrame window = new JFrame();
    window.setContentPane(new JScrollPane(content));
    window.setSize(200, 200);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
  }
}