2016-08-19 181 views
2

我想驗證JavaFX TextField中的數據輸入是否爲整數。我只想在用戶完全寫入輸入並移動到下一個字段後才執行此驗證。JavaFX TextField驗證

是否嘗試過的方法,但它不工作,我不明白爲什麼:

product_quantity.textProperty().addListener(new ChangeListener<String>() { 
    @Override 
    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { 
     if (!product_quantity.isFocused()) { 
      if (!product_quantity.getText().matches("[0-9]*")) { 
       total_cost.setStyle("-fx-background-color: red;"); 
      } else { 
       total_cost.setText(Float.toString(Float.parseFloat(newValue) * Float.parseFloat(unit_cost.getText()))); 
       total_cost.setStyle("-fx-background-color: white;"); 
      } 
     } 
    } 
}); 

如何才能做到這一點?

+0

是否有一個原因,你不只是設置TextField的[的TextFormatter](http://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextInputControl.html# textFormatterProperty)?例如:'textField.setTextFormatter(new TextFormatter(new NumberStringConverter(NumberFormat.getIntegerInstance())));' – VGR

+0

如果有無效項目,我必須將total_cost域框變爲紅色。當輸入正確完成後,我將刪除該顏色。 – Mohsin

+0

一個小問題,無論何時將顏色更改爲紅色,然後是白色,Fieldbox看起來都不像以前那樣。我怎樣才能把它恢復到原來的形式。我使用這個:'total_cost.setStyle(「 - fx-background-color:red;」);' – Mohsin

回答

3

您可以向focusProperty()添加偵聽器,而不是將偵聽器添加到textProperty()。這樣,只有當TextField丟失或接收焦點時,偵聽器纔會被觸發。

textField.focusedProperty().addListener((observable, oldValue, newValue) -> { 
    if(!newValue) { // we only care about loosing focus 
     // check condition and apply necessay style 
    } 
});