简体   繁体   English

动态添加JTable

[英]Add JTable dynamically

I have here the code when a button is clicked. 单击按钮时,这里有代码。 It is supposed to add a JTable in the JPanel regularPanel . 应该在JPanel regularPanel添加一个JTable The problem is that it doesn't show in the panel. 问题是它没有显示在面板中。

I added the panel in the frame via clicking the panel component. 我通过单击面板组件将面板添加到框架中。

    String[] columnNames = {"First Name",
                            "Last Name",
                            "Sport",
                            "# of Years",
                            "Vegetarian"};

    Object[][] data = {
        {"Kathy", "Smith",
         "Snowboarding", new Integer(5), new Boolean(false)},
        {"John", "Doe",
         "Rowing", new Integer(3), new Boolean(true)},
        {"Sue", "Black",
         "Knitting", new Integer(2), new Boolean(false)},
        {"Jane", "White",
         "Speed reading", new Integer(20), new Boolean(true)},
        {"Joe", "Brown",
         "Pool", new Integer(10), new Boolean(false)}
    };
    JTable table = new JTable(data,columnNames);
    table.setBounds(100, 100, 100, 80);
    JScrollPane tableContainer = new JScrollPane(table);
    regularPanel.add(tableContainer);

What should I do to view that table in the panel? 我应该怎么做才能在面板中查看该表?

Add your table to the JScrollPane viewport. 将表添加到JScrollPane视口。

Try the following: 请尝试以下操作:

TableModel tableDataModel = new AbstractTableModel() {
    public int getColumnCount() { return 2; }
    public int getRowCount() { return 5; }
    public Object getValueAt(int row, int col) { return new Integer(row*col); }
JTable table = new JTable(tableDataModel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().add(table);

In your button event handler, you should also be sure to call revalidate() and potentially repaint() once the table container is added to your panel. 在按钮事件处理程序中,一旦将表容器添加到面板后,还应确保调用revalidate()并可能调用repaint()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM