MyTableCellEditor 需要将覆盖编辑(如 Excel 单元格)和数据输入规则(parseDouble)添加到 JTable。当用户单击另一个单元格时,为什么单元格会擦除用户输入的值?IOW:输入到一个单元格中的值是可见的,直到单击另一个单元格,然后它就消失了。单步执行程序,当用户编辑单元格值时调用getTableCellEditorComponent,当单元格编辑完成时调用getCellEditorValue。
public class MyTableFrame extends javax.swing.JFrame
implements TableModelListener {
private static TableColumn column2;
public MyTableFrame() {
initComponents();
...
column2 = jTable.getColumnModel().getColumn(2);
column2.setCellEditor(new MyTableCellEditor());
jTable.getModel().addTableModelListener(this);
}
}
public class MyTableCellEditor extends AbstractCellEditor implements
TableCellEditor {
// Component to handle the editing of a cell value
private JTextField component = new JTextField();
// Return value
private Object value;
private DefaultTableModel model;
private int rowIndex;
private int columnIndex;
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int rowIndex, int columnIndex) {
model = (DefaultTableModel) table.getModel();
this.value = value;
this.rowIndex = rowIndex;
this.columnIndex = columnIndex;
component.setText("");
return component;
}
public Object getCellEditorValue() {
try {
return Double.parseDouble(model.getValueAt(rowIndex, columnIndex)
.toString());
} catch (Exception ex) {
return value;
}
}
}