tags:

views:

932

answers:

3

The high level: I have a JTable that the user can use to edit data.

Whenever the user presses Enter or Tab to finish editing, the data is saved (I'm asusming that "saved" really means "the TableModel's setValueAt() method is called".)

If the user leaves the cell in any other way after making an edit, the new data is not saved and the value stays the way it was. So, for example, if the user changes a value and then clicks on some other widget on the screen, the change doesn't "stick."

I believe that this is the default behavior for a JTable full of Strings, yes?

For a variety of reasons, the desired behavior is for the cell to save any and all edits whenever the user leaves the cell. What's the best/right way to get Swing to do this?

+2  A: 

You need to add a focus listener. Given that JTable is basically a container of its cell components, you actually want the focus listener for every cell in your table that needs to behave in the way you indicated.

To do this, you will need to create custom cell editor, which wraps the cell component that has a registered focus listener. And when you get the callback for the loss of focus event, you do the data save, as you require.

This pretty much details most of what you need to do. The details of implementing the focus listener is not there, but that is fairly straightforward.

Lets say you do use a JTextComponent as your cell component. Then:

public void focusLost(FocusEvent e) {
   JTextComponent cell = (JTextComponent) e.getSource();  
   String data = cell.getText();

   // TODO: save the data for this cell
}

[p.s. edit]:

The thread that is calling you with this event is the dispatch thread. Do NOT use it for actions with high latency. But if you are just flipping bits in the heap, it should be ok.

+3  A: 

Table Stop Editing explains whats happening and gives a couple simple solutions.

camickr
A: 

And where do I put addFocusListener, directly on the JTable object? I think it does not work so.

anna