从源代码进行一些增强和编辑:
public class RowSelectionListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent event) {
int viewRow = table.getSelectedRow();
if (!event.getValueIsAdjusting() && viewRow != -1) {
int columnIndex = 1;
// Better to access table row using modelRow rather than viewRow
int modelRow = table.convertRowIndexToModel(viewRow);
// Access value at selected row at the second column (columnIndex = 1)
Object modelvalue = table.getModel().getValueAt(modelRow, columnIndex);
// Not recommended: same as above but access row using viewRow
Object tablevalue = table.getValueAt(viewRow, columnIndex);
// Print cell value
System.out.println(modelvalue + "=" + tablevalue);
}
}
}
然后添加ListSelectionListener
到JTable
:
table.getSelectionModel().addListSelectionListener(new RowSelectionListener());
重要的提示:
viewRow
并modelRow
在应用时变得有效不同TableRowSorter
。