所以首先我创建了一个类比来让这个话题更容易理解。
我们有一支笔(editor
)。这支笔需要一些墨水(component
编辑器使用的,组件的示例JTextField
,JComboBox
等等)来书写。
然后这是一支特殊的笔,当我们想用笔写东西时,我们说话(在 GUI 中的打字行为)告诉它写东西(写在 中model
)。在写出之前,这支笔中的程序将评估单词是否有效(在stopCellEditing()
方法中设置),然后将单词写在纸上(model
)。
想解释@trashgod 的答案,因为我在该DefaultCellEditor
部分花了 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);
}
}
最后,在你的类中使用这行代码来初始化 JTable 来设置你的DefaultCellEditor
table.setDefaultEditor(Object.class,new PositiveIntegerCellEditor(new JTextField()));
表示您希望应用编辑器的Object.class
列类类型(您要使用该笔的纸张的哪一部分。可以是Integer.class
,Double.class
和其他类)。
然后我们传入new JTextField()
PositiveIntegerCellEditor() 构造函数(决定您希望使用哪种类型的墨水)。
如果有什么我误解了,请告诉我。希望这可以帮助!