如何验证jtable中只能接受移动号码的列?

时间:2012-03-08 06:41:29

标签: java hibernate swing jtable tablecelleditor

这就是我所做的;但是这些代码在某些情况下会失败,例如我们输入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);
    }
});

1 个答案:

答案 0 :(得分:2)

这是因为值9874561231超过了int max值。

您可以将验证更改为:

  1. 使用Long.parseLong()支持更大的值。

  2. 使用正则表达式检查字符串