Skip to content
Advertisement

How do you reliably know which JTable row has been selected from multiple tables if there is only one query button?

Tried on Ubuntu 20.04 in case it matters.
When multiple JTables are present, but you need to look at only the the last user selected row (or cell) of the last selected JTable, how can you reliably know which one that was? I’ve tried list select listeners and focus listeners, but all fail when you are editing a cell in both tables and you move between the same cells. For example, given the following code:

JavaScript

When you edit table 1, row 0, column 0 with anything new, and without pressing enter or clicking elsewhere other than table 2, row 1, column 0 and editing that one, when you click back on table 1, row 0, column 0, you don’t get any change notification (selection or focus). Going back and forth between editing both cells won’t let you know which one is currently being edited. The example above uses a button to print out the contents of the cell, but it can be any type of processing on the last selected cell that is needed.

Advertisement

Answer

You can detect focus change events on the editor’s Component by installing a FocusListener on it.

You can install your own editor (so that you have access to its installed Component) like so:

JavaScript

… or, if you want this behaviour on the pre-installed editor’s Component:

JavaScript

One of the above alternatives should go (by copy-paste) into the setupTable method. You can optionally combine that code with your ListSelectionListener (which you install on the ListSelectionModel) of the table. The FocusListener directly on the table itself seems not necessary for the purpose.

Also, don’t forget to change the second argument of the second call to setupTable (should be for example 2, not 1), otherwise use getSource(); on the FocusEvent received by the FocusListener (of the editor’s Component) methods.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement