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

一个人想着一个人 提交于 2020-02-07 19:39:29

问题


Is it possible to get or set the the cell value of a JTable by column name?


回答1:


Didn't find a built in method in JTable, but how about this:

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



回答2:


you can get a TableColumn from JTable's getColumn method, using the name of the column as the identifier; and get its 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.



来源:https://stackoverflow.com/questions/12034073/how-to-get-set-the-cell-value-of-a-jtable-by-its-column-name

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