0

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.

user3245747
  • 805
  • 2
  • 17
  • 30
  • similar to [Creating a Java Table Model which is initially empty but allows dynamic addition of rows by user](http://stackoverflow.com/questions/5311230/creating-a-java-table-model-which-is-initially-empty-but-allows-dynamic-addition) – Suzon Feb 23 '14 at 15:11
  • I don't see how my question is similar to the link you posted. I am not trying to add a new row. – user3245747 Feb 23 '14 at 15:54
  • Thanks. I managed to solve the problem by passing the JTable object to the verifier in order to access the getSelectedRow() method and it worked. – user3245747 Feb 24 '14 at 10:28

0 Answers0