Table Stop Editing
Posted by Rob Camick on December 12, 2008
When editing a cell in a JTable the table doesn’t know when a user is finished editing the cell. Therefore it is the users responsibility to tell the table when to stop editing. This is normally done by:
- using the enter key
- tabbing to the next cell
- clicking on another cell with the mouse
In all the above cases the table will stop the cell editing and save the value to the table model for you. However, there is one case that is not handled automatically by the table. That is, what should happen when a user clicks on a component other than the table?
Lets assume you have some buttons on your form that will take data from the table. In this case you would want the data to be saved automatically when the button is clicked. There are two options to solving this problem.
The first is to have the table automatically stop editing and save the data. This can be done by setting a property on the table:
JTable table = new JTable(...);
Note that this solution will cause the table to stop editing when any component get focus. I believe this logic is limited to components on the current window, but must admit I haven’t tested it. This solution will also not work when you click on the window buttons (ie, minimize or close).
Maybe the above solution is too general, and you want to control which components should stop editing. In this second case, you would need to add some code to the ActionListener of your buttons, something like:
This approach is a little more work, but it does give you full control as to when editing should be stopped.
It should be noted that clicking on a JTableHeader does not cause the table to lose focus. Therefore you will need to add a MouseListener to the table header and use the second approach to stop editing.