Shifting the focus from one cell to another in Jtable on tab press

前端 未结 2 1958
無奈伤痛
無奈伤痛 2021-01-22 08:36

Summary:

In my desktop application i load one Jtable and when in edit mode if i press tab i need the focus of the cell on to the next cell.

相关标签:
2条回答
  • 2021-01-22 09:18

    Off the top of my head, I think we overcame this with a custom keystroke implementation in the tabes InputMap & ActionMap.

    The implementation we use allows us to perform "continuous" editing, that is, when the user presses enter or tab, we move to the next editable cell and start editing

    InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    ActionMap am = table.getActionMap();
    
    KeyStroke tabKey = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
    
    Action moveNextCellAction = am.get(im.get(tabKey));
    
    ContinousEditAction continousEditAction = new ContinousEditAction(table, moveNextCellAction);
    
    im.put(tabKey, "Action.tab");
    
    am.put("Action.tab", continousEditAction);
    

    The ContinousEditAction is responsible for finding the next editable cell. Basically when the action is fired, you take stock of the current cell via JTable.getEditingRow & JTable.getEditingColumn methods (you also want to check that the table is edit mode via JTable.isEditing, otherwise you need to use JTable.getSelectedRow & JTable.getSelectedColumn - in fact you might get away with doing just this, but this is how I approached the problem).

    From there, you want to walk the cells until you find a cell that is editable.

    Basically, you want to check to the end of the current row, then move to the next until no more rows exist, depending on what you want to do, you may choose to loop back around to the start of the table (cell 0x0) and walk it until you reach your current position.

    Be careful, you can end up in a continuous loop if you're not careful :P.

    If you don't find any editable cells, you may simply wish to select the next available cell using JTable.setRowSelectionInterval & JTable.setRowSelectionInterval, other wise you can call JTable.editCellAt(nextRow, nextCol)

    But this all comes down to what it is you want to achieve.

    Also, you can apply the same idea to the enter key ;)

    0 讨论(0)
  • 2021-01-22 09:35

    Normally tab works in jTable once getting the focus .If you want to edit next cell by pressing Tab key give the following code in the key release event of jTable.

     if (evt.getKeyCode() == 9) {
                jTable1.editCellAt(nextRowIndex, nextColumnIndex);
        }
    
    0 讨论(0)
提交回复
热议问题