Java 动态更改 JTable 中的列标题文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1496143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:27:31  来源:igfitidea点击:

Dynamically changing the column header text in JTable

javaswingjtable

提问by sv_in

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]'.

我有一个包含 3 列的表格,其标题中有以下值:“No.”、“X [mm]”、“Y [mm]”。此表包含以毫米为单位的点坐标。我有一个复选框,用于检查应重新填充哪个表以显示以英寸为单位的坐标。此外,列标题值应为:“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.

详细说明: table 是 JTable 的子类。此外,“DefaultTableModel”的子类已被设置为表的模型。我已经在数据模型子类的构造函数中提供了标头值。

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

任何的想法?我的应用程序只与 jdk v1.4 兼容,所以如果解决方案与版本兼容就很好:)

采纳答案by camickr

You can update the TableColumnModel directly:

您可以直接更新 TableColumnModel:

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

回答by NawaMan

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

我无法在这里测试,但我很熟悉这个方法 ' [DefaultTableModel.setColumnIdentifiers(...)][1]' 应该做你想做的。

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(...)'.

基本上,您运行 ' DefaultTableModel.getColumnCount()' 来找出有多少列(除非您已经知道)。然后运行 ​​' DefaultTableModel.getColumnName(int ColumnIndex)' 以获取每个名称,按照您想要的方式更改它并将其放入数组中。之后,您可以使用“ DefaultTableModel.setColumnIdentifiers(...)”将它们重新设置。

Hope this helps.

希望这可以帮助。

回答by Jeus

If you have column number use that code

如果您有列号,请使用该代码

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