Dynamically changing the column header text in JTable

北城以北 提交于 2019-12-30 04:43:06

问题


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


回答1:


You can update the TableColumnModel directly:

JTableHeader th = table.getTableHeader();
TableColumnModel tcm = th.getColumnModel();
TableColumn tc = tcm.getColumn(0);
tc.setHeaderValue( "???" );
th.repaint();



回答2:


If you have column number use that code

 jtable.getColumnModel().getColumn(5).setHeaderValue("newHeader");



回答3:


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.



来源:https://stackoverflow.com/questions/1496143/dynamically-changing-the-column-header-text-in-jtable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!