Question

I am trying to enable a JButton when clicking "Ctrl+A" in a Jtable to select all rows, so I execute this code:

myTable.addKeyListener( new KeyListener() {         
    @Override
    public void keyReleased(KeyEvent e) {
        if( e.getKeyCode() == KeyEvent.VK_A && ( e.getModifiers() & InputEvent.CTRL_MASK ) != 0 ) {  // User clicked (CTRL + A) in table.
            if( myTable.getRowCount() > 1 )
                myButton.setEnabled( true );
        }
    }               
});

The problem is that many times this does not work ... Every time all rows in table are selected fine, but the button is not enabled! I have to click "Ctrl+A" 3 or 4 times for this to work. Is there something about that I should know, or a better idea for this to work?

Was it helpful?

Solution

Try overridding keyPressed instead of keyReleased.

OTHER TIPS

or a better idea for this to work ?

You should be using Key Bindings, not a KeyListener.

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