Java:为什么JTable不使用TableCellEditor?

时间:2010-11-02 13:12:26

标签: java jtable tablecelleditor

MyTableCellEditor的目的是使JTable单元的行为类似于Excel单元格,IOW,单击单元格后输入一个值,而不是附加到现有值。 我没想到下面的代码会在第一次传递时工作,但我确实希望在getTableCellEditorComponent和getCellEditorValue中遇到调试断点。 当我使用jTable时,为什么不调用getTableCellEditorComponent或getCellEditorValue?

public class MyTable extends javax.swing.JFrame implements TableModelListener {
    private static final MyTableCellEditor tableCellEditor =
        new MyTableCellEditor();
        ...
    public MyTable() {
        initComponents();
        jTable.getModel().addTableModelListener(MyTable.this);
        ...
    private void initComponents() { // Generated by the Form Editor.
        jTable = new javax.swing.JTable();
        jTable.setCellEditor(tableCellEditor);
        ...
public class MyTableCellEditor extends AbstractCellEditor implements
        TableCellEditor {
    JComponent component = new JTextField();
    public Component getTableCellEditorComponent(JTable table, Object value,
            boolean isSelected, int rowIndex, int vColIndex) {
        if (isSelected) {
            ((JTextField)component).selectAll();
        }
        ((JTextField)component).setText((String)value);
        return component;
    }
    public Object getCellEditorValue() {
        return ((JTextField)component).getText();
    }
}

1 个答案:

答案 0 :(得分:7)

setCellEditor(TableCellEditor)仅设置当前活动单元格的编辑器(一旦它不再处于活动状态,它将丢失。您想调用JTable.setDefaultEditor()来设置默认编辑器一个特定的班级。

jTable.setDefaultEditor(String.class, tableCellEditor);

或者,您可以通过TableColumnModel为列设置编辑器,例如

jTable.getColumnModel().getColumn(1).setCellEditor(tableCellEditor);