【问题标题】:Edit a specific cell in JTable on enter key and show the cursor在输入键上编辑 JTable 中的特定单元格并显示光标
【发布时间】:2013-08-22 00:26:40
【问题描述】:

我在框架上向 JTable 添加了一个 keylistner。 现在按着我有代码

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

这确实会编辑单元格,但直到我用鼠标单击它才会显示光标

【问题讨论】:

  • 为什么?编辑由TabelModel#isEditableTableCellEditor#isCellEditable控制

标签: java swing jtable keylistener tablecelleditor


【解决方案1】:

不要使用 KeyListener!

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

默认情况下:

  1. Enter 键会将单元格选择移动到下一行
  2. F2 键会将单元格置于编辑模式

所以你想用F2键的Action替换回车键的默认Action。这很容易通过使用键绑定来完成:

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));

另外,请查看Key Bindings 以获取所有 Swing 组件的默认绑定列表。

【讨论】:

    【解决方案2】:

    尝试为 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);
        }
    

    我希望这能奏效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 2014-08-29
      • 1970-01-01
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      相关资源
      最近更新 更多