0

I am creating a Java Fx Application using Scene Builder and jdk8. I have various textfields that look for numeric input. I want to be able to format these textfields once the textfield has lost focus.

I have been using DecimalFormat df = new DecimalFormat("######0.00"); on totalled result of textfields but not on the input textfields.

Any help greatly appreciated.

Decom1
  • 3
  • 1
  • 3
  • [add changeListener](http://stackoverflow.com/a/16971194/1315392) and call your format function when focus is lost – vinay Sep 22 '14 at 13:05
  • @vinay - I am new to event handling and up to now have only had to handle button actions. I have looked at focus listeners and know that there is a focus gained and lost methods but am unsure how to implement them. – Decom1 Sep 22 '14 at 13:12

2 Answers2

2
TextField tf1=new TextField();
TextField tf2=new TextField();
TextField tf3=new TextField();

// add focus listener to all textFields

tf1.focusedProperty().addListener(new TextFieldListener(tf1));
tf2.focusedProperty().addListener(new TextFieldListener(tf2));
tf3.focusedProperty().addListener(new TextFieldListener(tf3));

class implementing changeListener

class TextFieldListener implements ChangeListener<Boolean> {
          private final TextField textField ;
          TextFieldListener(TextField textField) {
            this.textField = textField ;
          }
           @Override
          public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
             if(!newValue)    // check if focus gained or lost
             {
                 this.textField.setText(getFormattedText(this.textField.getText());
             }
          }

     public String getFormatedText(String str)
     {
          //return formated text
     }
}
vinay
  • 1,121
  • 2
  • 12
  • 17
0
final ChangeListener<? super Boolean> focusListener = (o,ov,nv)->{
    if(!nv){
        TextField tf = (TextField)((ReadOnlyBooleanPropertyBase)o).getBean();
        //put your code here
    }
}
tf1.focusedProperty().addListener(focusListener);
tf2.focusedProperty().addListener(focusListener);
tf3.focusedProperty().addListener(focusListener);