This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

commitEdit() is not committing the value

 
Dalia Sultana
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have a JFormattedTextField as an editor in a JTable cell. If the user clicks on a different cell the value that the user just entered disappears, but on an enter it persists. To resolve the problem, I added a focus listener for the text field. So on focus lost I am calling commitEdit(). The value is still not persisting. I tried to go through the code in commitEdit, which showed that

format.stringToValue(getText()) --returns the old value.

It seems like the formatter some how did not return the new value.
This is how I am initializing the text field.

NumberFormat fmt2 = NumberFormat.getNumberInstance();
fmt2.setMinimumFractionDigits(9);
JFormattedTextField yearlyRateField = new JFormattedTextField(fmt2);
yearlyRateField .addFocusListener(new FocusListener(){

public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) {
yearlyRateField.commitEdit();
System.out.println(yearlyRateField.getValue());//this prints the old value
//yearlyRateField.setValue(23.1) //sets the value alright
}

});

Btw, I have a table cell listener, which updates the table model with the new value. After calling commitEdit, if I explicitly set a value to the text box, that value persists (as shown in the comment).
 
Brian Cole
Author
Ranch Hand
Posts: 903
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried
yourTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

It seems to me that you should be able to get the behaviour you want without having to mess with focus listeners.
 
Dalia Sultana
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have that property set on the table.
 
Brian Cole
Author
Ranch Hand
Posts: 903
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code works for me as is (except that yearlyRateField must be final and you must catch ParseException), and it also works if I comment out the entire FocusListener.

So presumably it's not this part of the code that's causing you trouble. If you're really using this as a table editor, you should probably show us all your TableCellEditor code, and perhaps also the code that attaches it to your JTable.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic