java-以编程方式启用在按键时编辑JTable单元格
作者:互联网
我想启用编辑键F2上的JTable单元的功能.
我知道默认情况下双击将启用编辑,但是有没有办法将该事件绑定到键?我尝试了此链接JTable edit on keypress,但对我不起作用.
这是我的代码:
public class DatabaseJTable extends JTable implements MouseListener {
public DatabaseJTable(Object [][] data, Object [] columnNames) {
super(data, columnNames);
InputMap inputMap = this.getInputMap(JComponent.WHEN_FOCUSED);
ActionMap actionMap = this.getActionMap();
this.addMouseListener(this);
// bind edit record to F2 key
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), "edit");
actionMap.put("edit", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
DatabaseJTable table = (DatabaseJTable)ae.getSource();
table.changeSelection(table.getSelectedRow(), 1, false, false);
table.editCellAt(table.getSelectedRow(), 1);
System.out.println("F2 pressed");
}
});
// binding delete record to Delete key
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
actionMap.put("delete", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
}
});
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
提前致谢.
解决方法:
F2已经是JTable用来开始编辑的默认KeyStroke.
有关所有组件使用的所有按键的表格,请参见Key Bindings.您还将找到使用键绑定的示例.
如果您确实创建了自己的操作,则应使用类似以下代码的方法:
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
if (editCellAt(row, column))
{
Component editor = table.getEditorComponent();
editor.requestFocusInWindow();
}
因此,一旦按下该键,编辑器就会获得焦点.
显然,Aqua LAF不会绑定F2,因此您似乎需要自己执行此操作.假设在ActionMap中定义了“ startEditing”操作,则可以使用:
KeyStroke keyStroke = KeyStroke.getKeyStroke("F2");
InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(keystroke, "startEditing");
标签:java,swing,jtable,key-bindings 来源: https://codeday.me/bug/20191010/1884477.html