这就是我所做的;但是此代码在某些情况下会失败,例如如果我们输入 9874561231,则无法插入此数字。
tbl.setCellEditor(new DefaultCellEditor(text){
@Override
public Object getCellEditorValue() {
// throws exception if parsing failes, and it's catched on stopCellEditing
return Integer.parseInt((String) super.getCellEditorValue());
}
@Override
public boolean stopCellEditing() {
boolean result = false;
try{
result = super.stopCellEditing();
((JTextField)getComponent()).setBackground(Color.WHITE);
lblEnterNumbersOnly.setVisible(false);
} catch (NumberFormatException e) {
((JTextField)getComponent()).setBackground(Color.RED);
lblEnterNumbersOnly.setVisible(true);
result = false;
}
return result;
}
@Override
public boolean isCellEditable(EventObject anEvent) {
// reset color when begin editing
((JTextField)getComponent()).setBackground(Color.WHITE);
return super.isCellEditable(anEvent);
}
});