When you click on a JTable cell, the row becomes "selected", I want it so that when I click on anything else, it becomes unselected.
I'm thinking of doing this with a mouse listener on the table but not sure how to recognize (click not on table). Any ideas?
This is what I'm trying:
jTable.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
System.out.println("click");}});
But it only prints click when I click in the first column and surely not when I click on something that's not the table.
When I recognize that event I'd call this method:
public void loseCellFocus()
{
jTable.getCellEditor().stopCellEditing();
jTable.clearSelection();
}
Use a
FocusListenerattached to theJTable, this will tell you when focus moves away from the table.See How to Write a Focus Listener for more details
For example...
This will, of course, only work when keyboard focus is transferred to a new component capable for receiving keyboard focus
You could use
JTable#setSurrendersFocusOnKeystrokeor check to see if the component that focus has been transferred to is a child of theJTableFor example...
Runnable Example...
Okay, that got messy. Not only did I have to add a
FocusListenerto theJTable, but I had to make sure one was added to theTableCellEditorcomponent :PThis is a proof of concept only, I'd have specialised classes which capable for either raising events or triggering the required functionality via some common interface
AWTEventListener Example...
Okay, didn't really want to go this route as it ends up in a mess of cross conditions, but. Basically this monitors ALL
MouseEventandFocusEvents, it does some backwards summersults to test for valid conditions (as we need to make sure that not only if aJTableis part of the event, but if the editor is part of the event) and based on those results, stops cell editing and clears the selection...This example basically works for ALL
JTables (once theAWTEventListeneris registered), but you could configure it to monitor a single table, by changing some of the event sources and comparing them to each other :P