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.
然后,当我们想用笔记来写一些东西时,我们就说(德国马克的定型行为)告诉它要写一些东西(载于<条码>model)。 在撰写本报告之前,本笔中的方案将评估该词是否有效(载于stopCellEditing(
)。
我愿解释一下@trashgod的回答,因为我已经在上花了4个小时。 该科。
//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);
}
}
最后,在您的级别上使用这一代号,以制定您的<代码>。
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).
如果我误解的话,请告诉我。 希望这一帮助!