I have a JTable which contains data that the user can edit. I want to make sure that when the user edits the "name" column, the new value is unique in the table, i.e. there are no other entries with the same name. I tried to do that using a custom cell editor and input verifier as follows:
class CellEditor extends DefaultCellEditor {
InputVerifier verifier = null;
public CellEditor(InputVerifier verifier) {
super(new JTextField());
this.verifier = verifier;
}
@Override
public boolean stopCellEditing() {
return verifier.verify(editorComponent) && super.stopCellEditing();
}
}
class MyVerifier extends InputVerifier {
DefaultTableModel tm = null;
MyVerifier(DefaultTableModel tm) {
super();
this.tm = tm;
}
@Override
public boolean verify(JComponent input) {
boolean verified = true;
String text = ((JTextField) input).getText();
for (int i = 0; i < tm.getRowCount(); i++) {
String s = (String) tm.getValueAt(i, 1);
if (s.equals(text)) {
verified = false;
break;
}
}
return verified;
}
}
In my code I used the following to set the cell editor to the specific column:
tm = (DefaultTableModel) myTable.getModel();
myTable.getColumnModel().getColumn(1).setCellEditor(new CellEditor(new MyVerifier(tm)));
The problem is that i always get that there is a duplicate value when I traverse the columns without changing anything because the loop in the verify method checks all the rows, including the focal row with itself. I want to exclude this case but I do not have access to the row number of the focal entry. Is there any other solution? Thanks.