仅使用行中包含的值在JTable中获取行索引? [英] Getting a row index in a JTable using only a value included in the row?

查看:101
本文介绍了仅使用行中包含的值在JTable中获取行索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,JTable是否可以通过查找该行中包含的指定值来获取该行的索引?我正在使用自定义表格模型.例如,考虑一个具有三列三行的表:

In Java, is it possible in a JTable to obtain a row's index by looking for a specified value contained in that row? I am using a custom table model. For example, consider a table with three columns and three rows:

Row 1 = A, B, C
Row 2 = D, E, F
Row 3 = G, H, I

如果我只知道表中某处有一个"F"值,我如何找出"F"值所在的行的索引?

If all I know is that there is a value of "F" somewhere in the table, how can I find out the index of the row where the value "F" is?

推荐答案

如果表模型可用,则强行方式是按行和列循环,并将给定值(例如'F')与getValueAt(row, column)的结果.示例代码:

If table model is available, a brute-force way is to loop it by row and column and compare the given value(say, 'F') with the result of getValueAt(row, column). Sample code:

 int getRowByValue(TableModel model, Object value) {
    for (int i = model.getRowCount() - 1; i >= 0; --i) {
        for (int j = model.getColumnCount() - 1; j >= 0; --j) {
            if (model.getValueAt(i, j).equals(value)) {
                // what if value is not unique?
                return i;
            }
        }
    }
 }

这篇关于仅使用行中包含的值在JTable中获取行索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆