[英]JTable Edit Cell only on double click and F2 and Not on any key press
I Have a JTable with some editable columns. 我有一个带有一些可编辑列的JTable。
If a cell is selected and I start typing, the cell enters into edit mode. 如果选择了一个单元格并且我开始输入,则单元格进入编辑模式。 I don´t want that.
我不想那样。 I want to edit the cell only if I press F2 or double click it.
我只想在按F2或双击它时编辑单元格。
I found some posts about key binding, but it didn´t help. 我发现了一些关于键绑定的帖子,但它没有帮助。
I´m newbie in Java. 我是Java的新手。 please be patient and clear.
请耐心,明确。
Another thing I notice. 我注意到的另一件事。 If I start editing by typing in cell, it has a different behavior than when I start edit the cell by F2 or double click.
如果我通过键入单元格开始编辑,它的行为与我开始通过F2或双击编辑单元格时的行为不同。 Why is that?
这是为什么?
You need to create your own TableCellEditor
and overwrite the method isCellEditable
: 您需要创建自己的
TableCellEditor
并覆盖方法isCellEditable
:
public class MyCellEditor extends AbstractCellEditor implements TableCellEditor {
private static final long serialVersionUID = 1L;
JTextField textField = new JTextField("");
@Override
public boolean isCellEditable(EventObject e) {
if (super.isCellEditable(e)) {
if (e instanceof MouseEvent) {
MouseEvent me = (MouseEvent) e;
return me.getClickCount() >= 2;
}
if (e instanceof KeyEvent) {
KeyEvent ke = (KeyEvent) e;
return ke.getKeyCode() == KeyEvent.VK_F2;
}
}
return false;
}
@Override
public Object getCellEditorValue() {
return this.textField.getText();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
this.textField.setFont(table.getFont());
this.textField.setText(value.toString());
return this.textField;
}
return false;
}
In isCellEditable
, I first call super.isCellEditable
to check for all other reasons why a cell could be editable or not. 在
isCellEditable
,我首先调用super.isCellEditable
来检查为什么单元格可以编辑的所有其他原因。 Only if it is editable per se, we check on our conditions. 只有它本身是可编辑的,我们才会检查我们的条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.