java 仅使用行中包含的值获取 JTable 中的行索引?

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

Getting a row index in a JTable using only a value included in the row?

javaswingindexingjtablerow

提问by ricgeorge

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:

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

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

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”值,我怎样才能找出值“F”所在行的索引?

回答by Hui Zheng

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:

如果表模型可用,一个蛮力的方法是按行和列循环它并将给定的值(例如,'F')与getValueAt(row, column). 示例代码:

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

回答by GGrec

 private int returnRowIndexForValue(final String value) { 
      for (int i = 1; i <= table.getRowCount(); i++)
           for(int j = 1; j <= table.getColumnCount(); j++)
                if (table.getValueAt(i, j).equals(value))
                     return i;
 }

回答by Amarnath

Just in case if there are multiple rowsthat are containing the value then return the return the Integer List.

以防万一,如果有multiple rows包含值然后返回返回Integer List.

private List<Integer> getRowIndexesOfValue(String value, JTable table) {

   List<Integer> rowNumbers = new ArrayList<Integer>();

   for(int rowCount = 0; rowCount < table.getRowCount(); rowCount++) {
      for(int columnCount = 0; columnCount < table.getColumnCount(); columnCount++) {
          if(table.getvalueAt(rowCount, columnCount).toString().equals(value)) {
             rowNumbers.add(rowCount);
             break;  
          }
       }
    }
    return rowNumbers;
}