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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12034073/
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-10-31 07:21:47  来源:igfitidea点击:

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

javaswingjtable

提问by Harsha

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

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

回答by Seyed Mohammad

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

回答by Jill Renee

you can get a TableColumn from JTable's getColumn method, using the name of the column as the identifier; and get its modelIndex....

您可以从 JTable 的 getColumn 方法中获取一个 TableColumn,使用列的名称作为标识符;并获取其模型索引....

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 中为你的表实现你需要的东西。