Java Swing How to - Get the component inside a JScrollPane








Question

We would like to know how to get the component inside a JScrollPane.

Answer

import java.awt.Component;
import java.awt.Dimension;
import java.util.Arrays;
import java.util.Vector;
//from ww  w . j ava  2  s. c om
import javax.swing.JFrame;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;

public class Main {
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Vector<Vector<String>> rowData = new Vector<Vector<String>>();
    Vector<String> columnName = new Vector<String>(Arrays.asList("Column 1"));
    for (int i = 0; i < 2000; i++) {
      rowData.add(new Vector<String>(Arrays.asList(Integer.toString(i))));
    }
    JTable table = new JTable(rowData, columnName);
    JScrollPane scrollPane = new JScrollPane(table);
    JScrollBar vertical = scrollPane.getVerticalScrollBar();
    vertical.setPreferredSize(new Dimension(0, 0));
    f.add(scrollPane);
    f.pack();
    f.setVisible(true);
    JViewport view = scrollPane.getViewport();
    Component[] components = view.getComponents();
    for (int i1 = 0; i1 < components.length; i1++) {
      if (components[i1] instanceof JTable) {
        System.out.println("got");
      }
    }
  }
}