Java Swing How to - Scroll a JScrollPane








Question

We would like to know how to scroll a JScrollPane.

Answer

import java.awt.Rectangle;
//  w  w  w  .  j ava2  s .  c o m
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class Main {
  String TEXT = "This \r\n" + "    Is\r\n" + "    A\r\n" + "    Testing\r\n"
      + "    To\r\n" + "    Test\r\n" + "    ScrollPane.";

  JTextArea jTextArea_content;
  JScrollPane jScrollPane_descContent;

  private void initUI() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getJTextArea_content().setText(TEXT);
    frame.add(getJScrollPane_descContent());
    frame.pack();
    frame.setVisible(true);
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        getJTextArea_content().scrollRectToVisible(new Rectangle());
      }
    });
  }

  private JTextArea getJTextArea_content() {
    if (jTextArea_content == null) {
      jTextArea_content = new JTextArea(3, 30);
      jTextArea_content.setBounds(new Rectangle(75, 224, 678, 47));
    }
    return jTextArea_content;
  }

  private JScrollPane getJScrollPane_descContent() {
    if (jScrollPane_descContent == null) {
      jScrollPane_descContent = new JScrollPane(getJTextArea_content());
      jScrollPane_descContent.setBounds(new Rectangle(75, 224, 660, 47));
    }
    return jScrollPane_descContent;
  }

  public static void main(String[] args) {
    new Main().initUI();
  }
}