Java : JFormattedTextField change setGroupingUsed() on focusLost & focusGained
-
24-03-2021 - |
Frage
I have many JFormattedTextdields with number data in it. I have used DecimalFormat, InternationalFormatter, DocumentListener and also tried with CaretPositionListener.
The only problem I face is caret position when number input grows and grouping character comes in between.
How can I dynamically set setGroupingUsed() of DecimalFormat of respective jformattedtextfields on focusGained & onFocusLost.
Any ideas or suggestions....
UPDATE CODE & PROBLEM : When I try to input "12345", on adding "1234" a comma appears "1,234". This brings to caret between 3 & 4 instead of after 4. The Formatting code I use :
DecimalFormat numberFormat = (DecimalFormat) DecimalFormat.getNumberInstance();
numberFormat.setMaximumFractionDigits(2);
numberFormat.setMinimumFractionDigits(2);
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
final InternationalFormatter formatter = new InternationalFormatter(numberFormat);
formatter.setAllowsInvalid(false);
formatter.setMinimum(0.00);
formatter.setMaximum(999999999.99);
return formatter;
This is what I have implemented as SOLUTION on a custom JFormattedTextField. Do you have any better approach to handle the grouping character while inputting value, so just caret position remains proper :
public void focusGained(FocusEvent e) {
if (numberFormat.isGroupingUsed()) {
Object o = this.getValue();
numberFormat.setGroupingUsed(false);
formatter.setFormat(numberFormat);
this.setFormatterFactory(new AbstractFormatterFactoryImpl());
this.setValue(o);
this.setText(o.toString());
}
}
public void focusLost(FocusEvent e) {
try {
this.commitEdit();
} catch (ParseException ex) {
//Logger.getLogger(NumberFormattedTextField.class.getName()).log(Level.SEVERE, null, ex);
}
Object o = this.getValue();
//System.out.println("focusLost : getValue = " + o);
numberFormat.setGroupingUsed(true);
formatter.setFormat(numberFormat);
this.setFormatterFactory(new AbstractFormatterFactoryImpl());
this.setValue(o);
this.setText(o.toString());
//System.out.println("focusLost : Text Set = " + o.toString());
}
Lösung
Thanks,
I solved by creating a custom textfield that manages everything I need. Any suggestion for improvements. Code is added above in question.