Padmanabhan
Padmanabhan

Reputation: 158

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.

Upvotes: 0

Views: 2726

Answers (2)

Michael McKay
Michael McKay

Reputation: 670

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

    }
}

Upvotes: 0

Nikolas
Nikolas

Reputation: 44398

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

Upvotes: 1

Related Questions