2013-10-26 57 views

回答

1

這種方法讓文本字段來完成所有處理(複製/粘貼/撤銷安全)。 不要求延長課程。 並允許您deside什麼的每一個變化 (將其推到邏輯,或將返回到之前的值,甚至修改)後,用新的文本做。

// fired by every text property change 
textField.textProperty().addListener(
    (observable, oldValue, newValue) -> { 
    // Your validation rules, anything you like 
     // (! note 1 !) make sure that empty string (newValue.equals("")) 
     // or initial text is always valid 
     // to prevent inifinity loop 
    // do whatever you want with newValue 

    // If newValue is not valid for your rules 
    ((StringProperty)observable).setValue(oldValue); 
     // (! note 2 !) do not bind textProperty (textProperty().bind(someProperty)) 
     // to anything in your code. TextProperty implementation 
     // of StringProperty in TextFieldControl 
     // will throw RuntimeException in this case on setValue(string) call. 
     // Or catch and handle this exception. 

    // If you want to change something in text 
     // When it is valid for you with some changes that can be automated. 
     // For example change it to upper case 
    ((StringProperty)observable).setValue(newValue.toUpperCase()); 
    } 
); 

爲了您的情況,只需將此邏輯放入其中,並將此偵聽器添加到所有文本字段中。完美的作品。

if (newValue.equals("")) return; 
    try { 
     // ammount entered 
    Integer i = Integer.valueOf(newValue); 
     // TextField used 
    TextField field = (TextField)((StringProperty)observable).getBean(); 
    // do what you want with this i and field 
    } catch (Exception e) { 
    ((StringProperty)observable).setValue(oldValue); 
    } 
相關問題