【问题标题】:Transfer focus in JTable在 JTable 中转移焦点
【发布时间】:2010-11-10 08:04:18
【问题描述】:

我想将单元格焦点转移到 JTable 中的特定单元格,例如当焦点在单元格 (2,3) 上并且按下回车键后,焦点应该转移到跳过的单元格 (2,5)一个单元格 (2,4)。

为此,我使用了 JTable 类的 changeSelection() 方法,但它不起作用。

【问题讨论】:

    标签: swing jtable


    【解决方案1】:

    应该只从那个确切的单元格 (2,3) 转移焦点还是转移到第 3 列中的所有单元格?无论如何,这是一个似乎可以满足您要求的示例。尽管请注意,此示例对 TableCellEditor 进行了以下假设:

    • TableCellEditor 应该在每次调用 #getTableCellEditorComponent 时返回相同的组件(因为我们向它添加了 KeyListener)
    • TableCellEditor 在询问不在表中的值时可能不会失败(如果在设置期间 TableModel 为空)

      table.setSurrendersFocusOnKeystroke(true);
      table.getCellEditor(2, 3).getTableCellEditorComponent(table, null, false, 2, 3).addKeyListener(new KeyAdapter()
      {
          @Override
          public void keyPressed(KeyEvent e)
          {
              if (e.getKeyCode() == KeyEvent.VK_ENTER && table.getSelectedRow() == 2 && table.getSelectedColumn() == 3)
              {
                  selectCell(2, 5);
                  table.editCellAt(2, 5);
                  focusEditedCell();
                  e.consume();
              }
          }
      
      
         private void selectCell(int row, int col)
         {
              table.setRowSelectionInterval(row, row);
              table.setColumnSelectionInterval(col, col);
         }
      
      
         private void focusEditedCell()
         {
             Component c = table.getEditorComponent();
             if (c != null)
             {
                c.requestFocusInWindow();
             }
         }
      });
      

    【讨论】:

    • 重要的部分是同时使用两者:table.setRowSelectionInterval(row, row); table.setColumnSelectionInterval(col, col);
    【解决方案2】:

    也许你可以在默认UI实现完成光标移动的地方找到答案。 jdk1.6.0_10\src\javax\swing\plaf\basic\BasicTableUI.java 我认为这是您正在寻找的潜在客户选择指数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 2010-09-30
      • 2011-11-20
      • 2012-05-29
      • 2012-10-03
      • 1970-01-01
      • 2012-06-16
      相关资源
      最近更新 更多