简体   繁体   English

如何创建仅包含列标题的JTable,不添加任何行

[英]How to Create a JTable with column headers only, no rows added

I am trying to create a JTable without any data rows, only column Headers added. 我试图创建一个JTable,不包含任何数据行,仅添加列标题。 How to do that? 怎么做? The idea is to add or remove rows later with button click event. 想法是稍后使用按钮单击事件添加或删除行。

It's simple, create a JTable using constructor new JTable(Vector rowData, Vector columnNames) , where rowData is the data for the new table and columnNames is names of each column. 很简单,使用构造函数new JTable(Vector rowData, Vector columnNames)创建一个JTable ,其中rowData是新表的数据, columnNames是每列的名称。 In case you want to create just a table with a header and no rows, make the Vector rows empty. 如果您只想创建一个没有标题的表而没有行,则将Vector rows空。

Vector rows = new Vector();
Vector headers = new Vector();
headers.addElement("Id");
headers.addElement("First name");
headers.addElement("Last name");

JTable table = new JTable(rows, headers);

There are many ways to create and define a JTable. 有很多创建和定义JTable的方法。 To do what you want, use the TableModel approach. 若要执行所需的操作,请使用TableModel方法。 You can define an empty model and fill it with data later. 您可以定义一个空模型,然后在其中填充数据。 See Creating a JTable for some examples. 有关一些示例,请参见创建JTable

Here is a simple demo of an empty table model. 这是一个空表模型的简单演示。

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

public class JTableDemo {

    public static void main(String args[]) {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        TableModel model = new DefaultTableModel();

        Object headers[] = { "Column One", "Column Two", "Column Three"};

        TableColumnModel columnModel = new DefaultTableColumnModel();
        TableColumn firstColumn = new TableColumn(1);
        firstColumn.setHeaderValue(headers[0]);
        columnModel.addColumn(firstColumn);

        TableColumn secondColumn = new TableColumn(0);
        secondColumn.setHeaderValue(headers[1]);
        columnModel.addColumn(secondColumn);

        TableColumn thirdColumn = new TableColumn(0);
        thirdColumn.setHeaderValue(headers[2]);
        columnModel.addColumn(thirdColumn);

        JTable table = new JTable(model, columnModel);

        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);

    }
}

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

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