Decom1
Decom1

Reputation: 3

JavaFx TextField focus lost formatting

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.

Upvotes: 0

Views: 4786

Answers (2)

Oleksandr Potomkin
Oleksandr Potomkin

Reputation: 339

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);

Upvotes: 0

vinay
vinay

Reputation: 1121

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
     }
}

Upvotes: 2

Related Questions