Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically changing the column header text in JTable

Tags:

java

swing

jtable

I have a table with 3 columns which have the following values in the headers: 'No.', 'X [mm]', 'Y [mm]'. This table contain the coordinates of points in millimeters. I have a checkbox on checking of which the table should repopulate to show the coordinates in inches. Moreover, the column header values should be: 'No.', 'X [in]', 'Y [in]'.

In short I want to dynamically change the header text of the table.

In detail: The table is a subclass of JTable. Moreover, a subclass of 'DefaultTableModel' has been set as the model for the table. I have provided the header values in the constructer of the datamodel subclass.

Any idea? My application is compatible with only jdk v1.4 so it would be good if the solution is compatible with the verion :)

like image 684
sv_in Avatar asked Sep 30 '09 04:09

sv_in


3 Answers

You can update the TableColumnModel directly:

JTableHeader th = table.getTableHeader();
TableColumnModel tcm = th.getColumnModel();
TableColumn tc = tcm.getColumn(0);
tc.setHeaderValue( "???" );
th.repaint();
like image 83
camickr Avatar answered Oct 24 '22 03:10

camickr


If you have column number use that code

 jtable.getColumnModel().getColumn(5).setHeaderValue("newHeader");
like image 11
Jeus Avatar answered Oct 24 '22 02:10

Jeus


I can't test here but familiar that this method '[DefaultTableModel.setColumnIdentifiers(...)][1]' should do what you want.

Basically, you run 'DefaultTableModel.getColumnCount()' to find out how many column (unless you already know). Then you run 'DefaultTableModel.getColumnName(int ColumnIndex)' to get the name of each, change it the way you want and put it in an array. After thatn, you set them back using 'DefaultTableModel.setColumnIdentifiers(...)'.

Hope this helps.

like image 3
NawaMan Avatar answered Oct 24 '22 01:10

NawaMan