简体   繁体   English

通过JTable中的列标题确定列名

[英]Determining a column name by column header in JTable

Is there any way to determine the column name by column header using Java JTable component? 有什么方法可以使用Java JTable组件通过列标题确定列名称? EG, I could have column header like "Header" and column name "Column". EG,我可以有“ Header”之类的列标题和“ Column”之类的列名称。 And I'm looking for a method like Column_Name_From_Header("Header") -> "Column". 而且我正在寻找类似Column_Name_From_Header(“ Header”)->“ Column”的方法。

If you have a reference to a JTable then the easiest way to obtain the column name is to obtain it from the underlying TableModel ; 如果您有对JTable的引用,那么获取列名的最简单方法是从基础TableModel获取它。 eg 例如

JTable tbl = ...
String colName = tbl.getModel().getColumnName(10);

This is typically desirable as access is done using model indices rather than view indices. 这通常是理想的,因为使用模型索引而不是视图索引来完成访问。 This means, for example that if you resort the columns of your JTable the column names in the model will still have the same predictable order. 这意味着,例如,如果您对JTable的列进行重新排序,则模型中的列名仍将具有相同的可预测顺序。

Iterate through the table columns of the table's column model. 遍历表的列模型的表列。 Find the one with the given header value (using headerValue.equals(tableColumn.getHeaderValue() ). Then ask the modelIndex of the column ( tableColumn.getModelIndex() ), and ask the table's model for the column name at this index : tableModel.getColumnName(index) . 找到具有给定标题值的值(使用headerValue.equals(tableColumn.getHeaderValue() )。然后询问列的modelIndextableColumn.getModelIndex() ),并在该索引的表模型中查询列名称: tableModel.getColumnName(index)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM