aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Using KeyListener with JTable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Using KeyListener with JTable" Watch "Using KeyListener with JTable" New topic
Author

Using KeyListener with JTable

Ste Graham
Greenhorn

Joined: Sep 15, 2003
Posts: 23
I'm having problems getting the same value for JTable.getSelectedRow() when using KeyEvents and MouseEvents. If I click on the very first table row, the value 0 is reported. However, if I then use the down key to get to row 1 (the second row in reality) getSelectedRow() reports 0 again (if I use the mouse to get to this row getSelectedRow reports 1 - which is correct). It gets even stranger when I then use the up key to get back to the first row in the table, getSelectedRow reports 1!! I'm unsure what is going on here - has anyone experienced this before? The MouseEvent reports back correctly, bu the KeyEvent isn't.
Stuart Gray
Ranch Hand

Joined: Apr 21, 2005
Posts: 410
Maybe this is a feature - the row being returned is the row that was selected *before* the KeyEvent was processed. So you press down, row 0 was previously selected. When you press up again, row was 1 selected. I don't know why this would happen though.

Do repeated calls to getSelectedRow() (without further keyevents) return the same value? Perhaps there is a delay in the event processing.
R.Joe
Ranch Hand

Joined: Jun 16, 2004
Posts: 31
u should use mouseListener like this

table.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
int X = e.getX();
int Y = e.getY();

int currentCol = getCurrentColumn(X,Y);
int currentRow = getCurrentRow(X,Y);
String str = getTableValueAt(cRow,cCol);
}
}
don't use getselectedrow, first dwtwct column and row then fetch a value when user click any row, i hope now ur problem get sorted off.
Stuart Gray
Ranch Hand

Joined: Apr 21, 2005
Posts: 410
But that won't help with the issue of keypresses, just mouse clicks.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
use keyReleased() instead of keyPressed()
Ste Graham
Greenhorn

Joined: Sep 15, 2003
Posts: 23
Well thanks for the help!! D'oh! I was catching the selected row (Jtable.getSelectedRow()) within the keyPressed() method. Of course when you press the key you start at the row you at, even though if you are pressing down you end up somehwere else. I did indeed use the keyReleased() method and this returned the value I was looking for. Once again thank you!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using KeyListener with JTable
 
Similar Threads
Help! MouseListener/JTable Question
prepareStatement Help
JTable problem
JTable and combobox as the cellEditor
JDO issue