Search code examples
javaswingjtablejtextfieldtablecelleditor

Dynamically change JTable cell value at focus lost


I have a JTable whose cell editor is a JTextField, I am invoking focuslost on the celleditor whose code is

public void focusLost(FocusEvent e)
{
 JTextField textField = new JTextField();
 textField = (JTextField) e.getSource();
 textField.setText(getCurrencyEquivalent(textField.getText()));//read P.S
 table.setValueAt(textField.getText(), table.getEditingRow(), 0);
}

I'm getting the following exception:

java.lang.ArrayIndexOutOfBoundsException: -1

When I debugged, it was clear that the focuslost is triggered on the cellEditor after the the focus is actually Lost from the JTable's cell. Which makes table.getEditingRow() always return -1, hence it is highly impossible to dynamically set the values at focuslost. Help me solve this by any other technique, if available.

P.S: getCurrencyEquivalent() is a method that returns a formatted version of a given String in a different String format.


Solution

  • getCurrencyEquivalent() is a method that returns a formatted version of a given String in a different String format.

    Don't use a FocusListener to try to change the format of the data when it is edited.

    Instead, you should be using a custom renderer to format the data. Check out Table Format Renderers for an easy example of how you can do this.