Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Enter Key from moving down a row in JTable

I need to override the enter key functionality on a JTable. At present the default behaviour is to move the row selection down one row when the user presses the 'Enter' key. I want to disable this and get it to do something different based on their selection. The problem is that it seems to move down before it goes into my keylistener which takes in the row selection - this therefore opens another window with the wrong row selected.

This is my code so far...:

public class MyJTable extends JTable {


   public MyJTable(){
        setRowSelectionAllowed(true);
        addListeners()
    }

    public void addListeners(){

         addKeyListener(new KeyListener() {
                @Override
                public void keyTyped(KeyEvent e) {}

                @Override
                public void keyPressed(KeyEvent e) {}

                @Override
                public void keyReleased(KeyEvent e) {
                    int key = e.getKeyCode();
                    if (key == KeyEvent.VK_ENTER) {

                        openChannel();
                    }
                }
           });
    }

    public void openChannel(){
            for (int selectedRow : getSelectedRows()){
                //Code to open channel based on row selected
            }
        }
}
like image 383
maloney Avatar asked Nov 22 '12 16:11

maloney


People also ask

What is JTable in swing?

The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet. This arranges data in a tabular form.

How can I tell if a row is selected in JTable?

JTable has a getSelectionModel() method which will give you a ListSelectionModel object. It tells you what rows are selected.

How do you clear a JTable row?

We can remove a selected row from a JTable using the removeRow() method of the DefaultTableModel class.


1 Answers

+1 to @Robin's answer

Adding to my comment...

Swing uses KeyBindings simply replace exisitng functionality by adding a new KeyBinding to JTable (the beauty happens because of JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT):

private void createKeybindings(JTable table) {
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
    table.getActionMap().put("Enter", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            //do something on JTable enter pressed
        }
    });
}

simply call this method and pass JTable instance to override standard functionality of JTable ENTER

like image 77
David Kroukamp Avatar answered Sep 29 '22 20:09

David Kroukamp