JavaFx TextField焦点丢失格式

时间:2014-09-21 22:51:29

标签: javafx textfield scenebuilder

我正在使用Scene Builder和jdk8创建Java Fx应用程序。我有各种文本字段,寻找数字输入。我希望能够在文本字段失去焦点后格式化这些文本字段。

我一直在使用DecimalFormat df = new DecimalFormat(“###### 0.00”);在文本字段的总计结果上,但在输入文本字段上没有。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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);