开发者

Prevent JTable cell editor from leaving "edit mode" on validation failure

I'd like to obtain the following behaviour in a JTable:

  • user starts editing a cell - the cell switches to a JTextField as usual;
  • when the user tabs out or clicks in another cell I'd like to validate the input and give a visual clue when validation fails (for example change the background color of JTextField) and prevent the cell开发者_运维知识库 from commiting AND switching back to default renderer (JLabel).

So far I've overridden DefaultCellEditor. I can hook into getCellEditorValue and make the validation there, but I don't know how to prevent the cell from going back to the default renderer.

Thanks!


What about JTable's method editingStopped()? See also

/**
        * Stops editing and
        * returns true to indicate that editing has stopped.
        * This method calls <code>fireEditingStopped</code>.
        *
        * @return  true 
        */         
     public boolean stopCellEditing() { 
        fireEditingStopped(); 
        return true;
    }

in the DefaultCellEditor


Here's how I made it to validate only for numeric data. It will color the bk red when validation fails.

column.setCellEditor(new DefaultCellEditor(new JTextField()){

  @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);
    }catch (NumberFormatException e) {
      ((JTextField)getComponent()).setBackground(Color.RED);
      result = false;
    }

    return result;
  }

  @Override
  public boolean isCellEditable(EventObject anEvent) {
    // reset color when begin editing
    ((JTextField)getComponent()).setBackground(Color.WHITE);
    return super.isCellEditable(anEvent);
  }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜