Question

I have to shift the cells up/down depending upon the up/down arrow key pressed from the keyboard. I am adding a KeyListener (in fact KeyAdapter) on the JTable to achieve it using the keyPressed() method. Now what's happening is that when I am pressing the alphanumeric keys, then I am able to get the selected row using table.getSelectedRow(), but when I am pressing the arrow keys its giving me "-1" always. That means no row is shown selected. I also tried to set the focus on table but it did not work. The code I am usin is as follows:

private void settingKeys() {
    controller.getStandardActionDetailsTableEquates().addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {

            System.out.println("key pressed!!");
            controller.getStandardActionDetailsTableEquates().setRowSelectionAllowed(true);
            int selectedRow = controller.getStandardActionDetailsTableEquates().getSelectedRow();
            System.out.println("selectedRow : " + selectedRow);

            controller.getStandardActionDetailsTableEquates().requestFocusInWindow();

            if (e.getKeyCode() == KeyEvent.VK_UP) {
                System.out.println("up arrow key pressed");

                Component editor = controller.getStandardActionDetailsTableEquates().getEditorComponent();
                editor.requestFocusInWindow();
                System.out.println("cursor : " + controller.getStandardActionDetailsTableEquates().getCursor());
                System.out.println("value : " + controller.getStandardActionDetailsTableEquates().getSelectedRow());

            } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                System.out.println("down arrow key pressed");
            }

        }
    });
}

I even tried to get the cursor position, but could not get it. Also, the editor found did not worked (shown in code). The "selected row" and "value" values are pining as "-1".

Please provide solution to this.

Was it helpful?

Solution

Don't use a KeyListener; use Key Bindings. JTable has the following default bindings in the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT input map:

  • VK_UP has the key "Table.selectPreviousRow"

  • VK_DOWN has the key "Table.selectNextRow".

You can replace the bindings with Action instances that update your TableModel as desired. This example may guide you. A complete listing can be obtained using the key binding utility cited here. Implementations may be found in the table's UI delegate, BasicTableUI, et al. The EditorKit actions, examined here, are also worth a look. Alternatively, consider a custom Comparator in your RowSorter, as shown here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top