jueves, 15 marzo 2007

Remove JTable's Enter Key behavior

« JTable Alternate Row Background | Main | JVM for Windows Mobile (J2ME) // PocketPC - PDA »

When you press the Enter key while in a JTable, you'll notice how the row selection changes to the next row or to the first row if the former row selected was the last row in the model. You can change this playing with the traversal key policy, but this is quite complicated.

The easy way is to consume the event if the enter key has been pressed. You can accomplish this doing the following:

JTable jMyTable = new JTable();
jMyTable.addKeyListener(new java.awt.event.KeyAdapter() {
     public void keyPressed(java.awt.event.KeyEvent evt) {
         jMyTableKeyPressed(evt);
     }
});
private void jMyTableKeyPressed(java.awt.event.KeyEvent evt) {
     if(evt.getKeyCode() == evt.VK_ENTER){
         evt.consume();
     }
}

It's very important to consume the event during the keyPressed event and not during the other possible keyEvents not doing so will mean that you will consume the event once it's been triggered, so the Enter key will continue advancing one row.

Technorati Tags:

Posted by admin at 2:38 PM in Java

 

[Trackback URL for this entry]

Comment: Randolf Richardson at lun, 2 ago 11:51 PM

This doesn't work. I've been trying to get JTable to behave properly (by not advancing the row when the user presses Enter), but this solution simply doesn't have this effect. Ditto for other solutions that Google found for me.

JTable rather sucks.

Comment: Jay Pagnis at jue, 7 oct 5:00 PM

Superb solution !! Programming Swing for years now and this has been my Achilles Heel !!

Your comment:

(not displayed)
 

SCode

Please enter the code as seen in the image above to post your comment.

 
 

Live Comment Preview:

 
Google
 
« March »
SunMonTueWedThuFriSat
    123
45678910
11121314151617
18192021222324
25262728293031