JTable的默认行为是在您开始输入时附加到内容,并在点击时将插入符放置在点击的位置.我想要这些东西的行为改变,所以当我编辑一个单元格,通过输入或通过单击,然后打字,内容被替换.当我单击一个单元格,然后更改插入符号位置,但是,我想要保留内容,所以我可以更改它.
我知道如何在单元格编辑时选择全部,通过用SwingUtilities.invokeLater(参见elsewhere)中的所有选项替换单元格编辑器,但会导致打字行为中断.当我这样做并开始输入单元格时,首先将类型化的字符附加到字符串,然后选择它(但是选择是不可见的!),并且当输入另一个字符时,内容被替换.
当输入突出显示(但不是编辑)单元格时,是否有方法立即替换内容,但是在单击单元格时全选?
这是CellEditor使用的代码:
public class TextFieldCellEditor extends JTextField implements TableCellEditor { private CellEditorListener cellEditorListener = null; private boolean isInteger = false; private Object oldValue; // Start editing @Override public Component getTableCellEditorComponent(JTable table,Object obj,boolean isSelected,int row,int column) { Color color2 = DefaultLookup.getColor(this,ui,"Table.alternateRowColor"); super.setBackground(color2 != null && (row & 1) == 1? color2 : table.getBackground()); super.setForeground(table.getForeground()); super.setBorder(DefaultLookup.getBorder(this,"Table.focusCellHighlightBorder")); super.setText(obj.toString()); isInteger = obj instanceof Integer; if (isInteger) { super.setHorizontalAlignment(SwingConstants.RIGHT); oldValue = obj; } // SwingUtilities.invokeLater(new Runnable() // { // public void run() // { // TextFieldCellEditor.this.selectAll(); // } // }); return this; } // Retrieve e dited value @Override public Object getCellEditorValue() { if (isInteger) { // Try to convert to integer. If input is invalid,revert. try { return new Integer(super.getText()); } catch (NumberFormatException e) { return oldValue; } } return super.getText(); } @Override public boolean isCellEditable(EventObject e) { return true; } @Override public boolean shouldSelectCell(EventObject e) { return true; } @Override public boolean stopCellEditing() { cellEditorListener.editingStopped(new ChangeEvent(this)); return true; } @Override public void cancelCellEditing() { cellEditorListener.editingCanceled(new ChangeEvent(this)); } @Override public void addCellEditorListener(CellEditorListener celleditorlistener) { cellEditorListener = celleditorlistener; } @Override public void removeCellEditorListener(CellEditorListener celleditorlistener) { if (cellEditorListener == cellEditorListener) cellEditorListener = null; } }
解决方法
在您的getTableCellEditorComponent()实现中,添加以下内容:
if (isSelected) { this.selectAll(); }
另外,为什么不扩展AbstractCellEditor或DefaultCellEditor(JTextField textField)?参见How to Use Tables: Using Other Editors.