user2035041
user2035041

Reputation: 69

Edit a specific cell in JTable on enter key and show the cursor

I have added a keylistner to JTable on frame. Now on kepressed i have the code

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

this does edit the cell but the cursor is not shown till i click on it by mouse

Upvotes: 0

Views: 3311

Answers (2)

repot
repot

Reputation: 83

Try add Robot for 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);
    }

I hope this work.

Upvotes: 0

camickr
camickr

Reputation: 324108

Do not use a KeyListener!

Swing was designed to use Key Bindings (see the Swing tutorial on How to Use Key Bindings). That is you bind an Action to a KeyStroke.

By default:

  1. The Enter key will move the cell selection to the next row
  2. The F2 key will place a cell in edit mode

So you want to replace the default Action of the Enter key with the Action of the F2 key. This is easily done by using Key Bindings:

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

Also, check out Key Bindings for a list of the default bindings for all Swing components.

Upvotes: 5

Related Questions