سؤال

To get the selected row in a jTable, I used a MouseEvent (MouseClicked). That works fine and give me the correct rownumber after clicking into the table.

To navigate trough the jTable, I added a new Listener (KeyPressed). If I press the up key, the rownumber is not been increased. If I press the up key again, the rowcount will be updated, but it is the rowcount from previously.

private void jTable1KeyPressed(java.awt.event.KeyEvent evt) { 
    if(evt.getKeyCode() == evt.VK_UP){
     System.out.println("Key UP" + jTable1.getSelectedRow()); 
    } 

    if(evt.getKeyCode() == evt.VK_DOWN){ 
    System.out.println("Key DOWN" + jTable1.getSelectedRow()); 
    }
}

This is the simple code. If I click into first row of table and press the down key, the output is "Key DOWN0". But the second row is selected and output should be "Key DOWN1".

هل كانت مفيدة؟

المحلول

To get the selected row in a jTable, I used a MouseEvent (MouseClicked). That works fine and give me the correct rownumber after clicking into the table.

To navigate trough the jTable, I added a new Listener (KeyPressed). If I press the up key, the rownumber is not been increased. If I press the up key again, the rowcount will be updated, but it is the rowcount from previously

.

I think that you would need to

نصائح أخرى

@mKorbel already posted the correct answer: don't use low-level listeners for semantic requirements - ListSelectionModel/-Event hides all the low-level knitty-gritty details :-)

The details:

  • JTable's internals have keyBindings to the up/down keys which change the selection
  • keyBindings are served after the listeners

So at the time of your application code seeing the event, the table didn't yet had the opportunity to react - what you are printing is the selection before its internal change (triggered by the bindings).

You should use KeyReleased instead of KeyPressed

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top