2013-08-20 25 views
0

我已经在框架上向JTable添加了键列表。 现在对kepressed我的代码在输入键上编辑JTable中的特定单元格并显示光标

  if (ke.getKeyCode()==10) 
      { 
       int rowIndex = jTable2.getSelectedRow(); 
       int colIndex = jTable2.getSelectedColumn(); 
       jTable2.editCellAt(rowIndex, colIndex); 
       ke.consume(); 

这样做编辑的细胞,但直到我点击它的鼠标

+1

为什么?编辑由'TabelModel#isEditable'和'TableCellEditor#isCellEditable'控制。 – MadProgrammer

回答

4

不要使用KeyListener的光标不显示!

Swing旨在使用密钥绑定(请参见How to Use Key Bindings上的Swing教程)。那就是你将一个Action绑定到KeyStroke。

默认:

  1. Enter键将小区选择移动到下一行
  2. F2键将放置一个细胞在编辑模式下

所以,你要更换使用F2键的操作执行Enter键的默认操作。这很容易通过使用密钥绑定完成:

InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); 
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); 
KeyStroke f2 = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0); 
im.put(enter, im.get(f2)); 

此外,对于所有Swing组件的默认绑定列表检查Key Bindings

+0

+1 yes ......................... – mKorbel

0

尝试添加机器人为F2的keyPressed:

if (ke.getKeyCode()==10) 
    { 
     int rowIndex = jTable2.getSelectedRow(); 
     int colIndex = jTable2.getSelectedColumn(); 
     jTable2.editCellAt(rowIndex, colIndex); 
     ke.consume(); 

     Robot pressF2 = null; 
     try { 
      pressF2 = new Robot(); 
     } catch (AWTException ex) { 
      System.err.println(ex.getMessage()); 
     } 
     pressF2.keyPress(KeyEvent.VK_F2); 
    } 

我希望这项工作。

相关问题