简体   繁体   中英

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. 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. In case you want to create just a table with a header and no rows, make the Vector rows empty.

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. To do what you want, use the TableModel approach. You can define an empty model and fill it with data later. See Creating a JTable for some examples.

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);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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