Java Swing How to - Get view position for JScrollPane








Question

We would like to know how to get view position for JScrollPane.

Answer

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;
/*www  . j  a  va2s.  c  om*/
public class Main {

  public static void main(String[] args) {
    String text = "one\ntwo\nthree\nfour\nfive";
    JFrame frame = new JFrame("title");
    JTextArea textArea = new JTextArea(text, 1, 30); // shows only one line
    JScrollPane scrollPane = new JScrollPane(textArea);
    frame.add(scrollPane);
    frame.pack();
    frame.setVisible(true);

    final JViewport viewport = scrollPane.getViewport();

    textArea.addCaretListener(e -> {
      System.out.println("First : " + viewport.getViewPosition());
      System.out.println("Second: " + viewport.getViewPosition());
    });
    textArea.setCaretPosition(text.length());
  }
}