如何在JScrollPane中获取组件

时间:2011-12-05 13:12:05

标签: java swing user-interface jtable jscrollpane

我在JScrollPane中有一个JTable;我如何获得JTable?

由于

2 个答案:

答案 0 :(得分:5)

JViewport viewport = scrollPane.getViewport(); 
JTable mytable = (JTable)viewport.getView();

答案 1 :(得分:1)

您必须从JTable中提取JViewport,从JViewport提取JScrollPane

import java.awt.Component;
import java.awt.Dimension;
import javax.swing.*;
import java.util.Arrays;
import java.util.Vector;

public class SingleTableTest extends JFrame {

    private static final long serialVersionUID = 1L;

    public SingleTableTest() {
        setDefaultCloseOperation(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, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        JScrollPane scrollPane = new JScrollPane(table);
        JScrollBar vertical = scrollPane.getVerticalScrollBar();
        vertical.setPreferredSize(new Dimension(0, 0));
        add(scrollPane);
        pack();
        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("Hehehehr here is heídden that JTable");
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new SingleTableTest();
            }
        });
    }
}