JTable 修改某行后, 行数据验证失败(如:主键冲突) , 禁止选取其它行, 弹出对话框提示用户有主键冲突,或某字段不能为空。取消对话框后,当前行仍选择, 除非按下ESC键,取消修改。

解决方案 »

  1.   

    编辑后,焦点离开此行时,我会验证主键有无冲突, 如果存在冲突,则焦点不可以失去,除非按下ESC键,放弃编辑 (如果是新增行,则删除;修改行,则复原数据)。我这里说的焦点,不是指光标,是当前选定的单元格, 无论何时,表格中都有一个选定cell
      

  2.   

    自定义主键那一列使用的 TableCellEditor下面是 CellEditor 里面 stopCellEditing 方法的源码注释:
        /**
         * Tells the editor to stop editing and accept any partially edited
         * value as the value of the editor.  The editor returns false if
         * editing was not stopped; this is useful for editors that validate
         * and can not accept invalid entries.
         *
         * @return true if editing was stopped; false otherwise
         */
        public boolean stopCellEditing();
      

  3.   

    自己定义了 TableCellEditor 以后,设置到 JTable 的方法跟 TableCellRenderer 类似,可以按数据类型设置:jtable.setDefaultEditor(Class<?>, TableCellEditor);也可以给某列设置:jtable.getColumnModel().getColumn(int).setCellEditor(TableCellEditor);