简体   繁体   English

如何通过其列名获取/设置JTable的单元格值

[英]How to get/set the cell value of a JTable by its column name

是否可以通过列名获取或设置JTable的单元格值?

Didn't find a built in method in JTable, but how about this: 在JTable中找不到内置方法,但是如何处理:

private int getColumnByName(JTable table, String name) {
    for (int i = 0; i < table.getColumnCount(); ++i)
        if (table.getColumnName(i).equals(name))
            return i;
    return -1;
}

Then you can use the following to set & get cell values : 然后,您可以使用以下设置和获取单元格值:

table.setValueAt(value, rowIndex, getColumnByName(table, colName));

table.getValueAt(rowIndex, getColumnByName(table, colName));

you can get a TableColumn from JTable's getColumn method, using the name of the column as the identifier; 您可以使用列名作为标识符从JTable的getColumn方法获取TableColumn; and get its modelIndex.... 并获取其modelIndex。

but if your table has sorting; 但是,如果您的表格已排序; then you need to do translation. 那么您需要翻译。

I'd recommend implementing what you need in the tableModel for your table. 我建议在表的tableModel中实现所需的功能。

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

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