private static class JTable.GenericEditor使用内省来捕获通过使用无效的String值构造特定Number子类引发的异常.如果您不需要这样的通用行为,请考虑将ActiveIntegerCellEditor创建为
DefaultCellEditor的子类.您的stopCellEditing()方法将相应更简单.
附录:已更新以使用RIGHT对齐方式和常见错误代码.
private static class PositiveIntegerCellEditor extends DefaultCellEditor {
private static final Border red = new LineBorder(Color.red);
private static final Border black = new LineBorder(Color.black);
private JTextField textField;
public PositiveIntegerCellEditor(JTextField textField) {
super(textField);
this.textField = textField;
this.textField.setHorizontalAlignment(JTextField.RIGHT);
}
@Override
public boolean stopCellEditing() {
try {
int v = Integer.valueOf(textField.getText());
if (v < 0) {
throw new NumberFormatException();
}
} catch (NumberFormatException e) {
textField.setBorder(red);
return false;
}
return super.stopCellEditing();
}
@Override
public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column) {
textField.setBorder(black);
return super.getTableCellEditorComponent(
table,value,isSelected,row,column);
}
}