need to handle JTable's rows using arrow keys from the keyboard

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() {
        public void keyPressed(KeyEvent e) {

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


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

                Component editor = controller.getStandardActionDetailsTableEquates().getEditorComponent();
                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.


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. Alternatively, consider a custom Comparator in your RowSorter, as shown here.

Need Your Help

Using Django REST Framework API for data model with composite key

python django rest django-rest-framework

How do you use Django Rest Framework to create an API when the data model has a composite key consisting of two fields? Background: I am trying to make a REST api for a data model (sample data row ...

While Loop skipping scanf for it's condition.

c loops while-loop char

I can't see why does the While loop just speed away and skipping the scanf for the char?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.