编程语言
首页 > 编程语言> > java – 访问包含JTable的JScrollpane

java – 访问包含JTable的JScrollpane

作者:互联网

我在JScrollpane中有一个JTable.我无权访问JScrollpane变量.但我可以访问JTable.现在我如何使用JTable访问JScrollpane.

For Example -> mytable.getAncestor(...) or something?

解决方法:

如果你想从JTable中获取JScrollPane

JTable jTable = new JTable(rowData, colData);
JScrollPane scrollPane = new JScrollPane(jTable);
// now you have the ViewPort
JViewport parent = (JViewport)jTable.getParent();
JScrollPane enclosing = (JScrollPane)parent.getParent();

试试下面的代码..

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRootPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;

/**
 *
 * @author Patrick Ott <Patrick.Ott@professional-webworkx.de>
 * @version 1.0
 */
public class MainFrame extends JFrame {

    private String[][] rowData = 
    {
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Max", "Mustermann", "Musterhausen"},
        {"Petra", "Mustermann", "Musterhausen"}
    };

    private String[] columnData = 
    {
        "Firstname", "Lastname", "City"
    };
    private JTable jTable;

    public MainFrame() {
        jTable = new JTable(rowData, columnData);
        jTable.setName("CRM Table");
    }

    public void createAndShowGui() {
        this.setTitle("JTable in JScrollPane");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.getContentPane().add(new JLabel("CRM System"), BorderLayout.NORTH);
        JScrollPane scrollPane = new JScrollPane(jTable);
        this.getContentPane().add(scrollPane, BorderLayout.CENTER);
        this.setSize(new Dimension(1024, 768));
        this.setVisible(true);
        Container parent = jTable.getParent().getParent();
        JScrollPane enclosing = (JScrollPane)parent;
        parent.remove(jTable);
        parent.add(new JLabel("Test"));
        // System.out.println(enclosing.getClass().getSimpleName());
    }
}

帕特里克

标签:java,swing,jtable,jscrollpane,swingutilities
来源: https://codeday.me/bug/20190612/1226199.html