Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set header for JTable?

Tags:

java

swing

With below example code:

String column_names[]= {"Serial Number","Medicine Name","Dose","Frequency"};
table_model=new DefaultTableModel(column_names,3);
table=new JTable(table_model);

We want to set header with names of columns as in column_names with the above code but it is not working. Header is not visible though table is getting created.

like image 369
newbee Avatar asked Feb 19 '10 16:02

newbee


People also ask

How to Set header JTable in Java?

With below example code: String column_names[]= {"Serial Number","Medicine Name","Dose","Frequency"}; table_model=new DefaultTableModel(column_names,3); table=new JTable(table_model); We want to set header with names of columns as in column_names with the above code but it is not working.

How add column in JTable in Netbeans?

Right-click the table and select "Properties." The table's properties display, including the columns. You click a column and change the heading to edit the current columns. To add a new column, click "New" and type a heading for the column.

What is default table model in Java?

Class DefaultTableModel. This is an implementation of TableModel that uses a Vector of Vectors to store the cell value objects. Warning: DefaultTableModel returns a column class of Object .


2 Answers

To be able to see the header, you should put the table in a JScrollPane.

panel.add(new JScrollPane(table));

Or you could specifically add the tableHeader to your panel if you really don't want a scrollpane (but: normally you don't want this behaviour):

panel.add(table.getTableHeader(), BorderLayout.NORTH);
panel.add(table, BorderLayout.CENTER);
like image 88
Fortega Avatar answered Sep 21 '22 20:09

Fortega


See here for more information about JTables and TableModels

JTable Headers only get shown when the Table is in a scroll pane, which is usually what you want to do anyway. If for some reason, you need to show a table without a scroll pane, you can do:

panel.setLayout(new BorderLayout());
panel.add(table, BorderLayout.CENTER);
panel.add(table.getTableHeader(), BorderLayout.NORTH);
like image 38
Reverend Gonzo Avatar answered Sep 21 '22 20:09

Reverend Gonzo