如何在 JTable 重新排序时跟踪列索引?

How to Keep Track of colem index when JTable has been Reordering?

我有 jTable,它有像 folow 这样的 colems 名称 :-

columns = {"ID", "NAME", "PHONE"};

包含值:

----------------------------
|ID |   NAME   |   PHONE   |
----------------------------
| 1 |   Adeeb  |   0750000 |
| 2 |   Jack   |   0777777 |
----------------------------

此 jTable 允许重新排序:

jTable1.getTableHeader().setReorderingAllowed(true);

我有一个按钮可以从 Colem“Name”获取值:

   for (int k = 0; k < jTable1.getRowCount(); k++) {

        String qty = (String) jTable1.getValueAt(k, jTable1.getColumn("NAME").getModelIndex());
        
        JOptionPane.showMessageDialog(null, "Name Is : " + qty);

    }

获取值如下:

Name Is : Adeeb
Name Is : Jack

但如果用户按以下示例排列字段:

------------------------------
|ID |   PHONE    |   Name    |
------------------------------
| 1 |   0750220  |    Adeeb  |
| 2 |   0777777  |    Jack   |
------------------------------

获取值如下:

Name Is : 0750220
Name Is : 0777777

我需要它像以前一样给我结果,所以我需要它来跟踪“名称”列并从中获取价值,即使用户重新排序也是如此!

通过这个修复它:

TableColumnModel tcms = jTable1.getColumnModel();

    for (int k = 0; k < jTable1.getRowCount(); k++) {

    int location = tcms.getColumnIndex(model.getColumnName(1));

    String qty = (String) jTable1.getValueAt(k, location);

    JOptionPane.showMessageDialog(null, qty);
}

从 TableModel 获取数据。模型中的数据未重新排序。

String name = table.getModel.getValueAt(row, 2);

或者要从 table 中获取数据,您需要使用:

int columnIndex = table.modelToView(2);
String name = table.getValueAt(row, columnIndex);