そこで、まず、このトピックを理解しやすくするために類推を作成しました。
私たちはペン( editor
)を持っています。このペンを書くには、いくらかのインク (component
エディターが使用するもの、コンポーネントの例は などJTextField
)JComboBox
が必要です。
次に、これはペンを使用して何かを書きたい場合の特別なペンであり、話す (GUI での入力動作) ことで、何かを書くように伝えます (に書き込みますmodel
)。書き出す前に、このペンのプログラムは単語が有効かどうかを評価し (stopCellEditing()
メソッドで設定されます)、単語を紙に書き出します ( model
)。
セクションに4時間費やしたので、@trashgodの答えを説明したいと思いますDefaultCellEditor
。
//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() コンストラクター (使用するインクの種類を決定します) を渡します。
私が誤解したことがあれば教えてください。お役に立てれば!