As I understand the question, it's about validating the input in the editor (the model protecting itself against invalid values is another story, IMO) and notifying the user about his/her error when s/he tries to commit the input.
A simple means of doing so is using an InputVerifier:
- implement the validation rule in its verify method
- implement the notification in its shouldYieldFocus
- subclass DefaultCellEditor and override its stopCellEditing to call shouldYieldFocus and return its result (aka: refuse to commit the edit)
Some code snippet:
final InputVerifier iv = new InputVerifier() {
@Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
return field.getText().length() > 8;
}
@Override
public boolean shouldYieldFocus(JComponent input) {
boolean valid = verify(input);
if (!valid) {
JOptionPane.showMessageDialog(null, "invalid");
}
return valid;
}
};
DefaultCellEditor editor = new DefaultCellEditor(new JTextField()) {
{
getComponent().setInputVerifier(iv);
}
@Override
public boolean stopCellEditing() {
if (!iv.shouldYieldFocus(getComponent())) return false;
return super.stopCellEditing();
}
@Override
public JTextField getComponent() {
return (JTextField) super.getComponent();
}
};
JTable table = new JTable(10, 2);
table.setDefaultEditor(Object.class, editor);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…