So first I created an analogy to make this topic easier to be understood.
We have a pen(editor
). This pen will need some ink(The component
that the editor use, an example of a component is JTextField
,JComboBox
and so on) to write.
Then this is a special pen when we want to write something using the pen, we speak(typing behavior in the GUI) to tell it to write something(write in the model
). Before writing it out, the program in this pen will evaluate whether the word is valid(which being set in stopCellEditing()
method), then it writes the words out on paper(model
).
Would like to explain @trashgod's answer since I have spent 4 hours on the DefaultCellEditor
Section.
//first, we create a new class which inherit DefaultCellEditor
private static class PositiveIntegerCellEditor extends DefaultCellEditor {
//create 2 constant to be used when input is invalid and valid
private static final Border red = new LineBorder(Color.red);
private static final Border black = new LineBorder(Color.black);
private JTextField textField;
//construct a `PositiveIntegerCellEditor` object
//which use JTextField when this constructor is called
public PositiveIntegerCellEditor(JTextField textField) {
super(textField);
this.textField = textField;
this.textField.setHorizontalAlignment(JTextField.RIGHT);
}
//basically stopCellEditing() being called to stop the editing mode
//but here we override it so it will evaluate the input before
//stop the editing mode
@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;
}
//if no exception thrown,call the normal stopCellEditing()
return super.stopCellEditing();
}
//we override the getTableCellEditorComponent method so that
//at the back end when getTableCellEditorComponent method is
//called to render the input,
//set the color of the border of the JTextField back to black
@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);
}
}
Lastly, use this line of code in your class that initialise JTable to set your DefaultCellEditor
table.setDefaultEditor(Object.class,new PositiveIntegerCellEditor(new JTextField()));
The Object.class
means which type of column class you wish to apply the editor
(Which part of paper you want to use that pen. It can be Integer.class
,Double.class
and other class).
Then we pass new JTextField()
in PositiveIntegerCellEditor() constructor(Decide which type of ink you wish to use).
If anything that I misunderstood please tell me. Hope this helps!