2016-07-16 181 views
1

我需要一些幫助。我有一個ArrayListTextfield s。JavaFX TextField監聽器

static List<TextField> lfLetters = new ArrayList<>(); 

我想檢查一下值是否已經改變。如果是這樣,我想知道它是哪個文本框。我知道我可以用Listener來做到這一點,但只適用於單個人。

TextField textField = new TextField(); 
textField.textProperty().addListener((observable, oldValue, newValue) -> { 
    System.out.println("textfield changed from " + oldValue + " to " + newValue); 
}); 

我想讓它在一個數組上工作並確定哪個文本字段已經改變。

在此先感謝!

回答

2

您可以使用ObservableList適當的提取和直接添加監聽器列出。這樣它將自動監視其元素指定屬性的更改。這是更方便,比添加的偵聽到每個文本字段,但在這種情況下,你不能讓舊值:簡單地做`最終詮釋指數

ObservableList<TextField> oList = 
     FXCollections.observableArrayList(tf -> new Observable[]{tf.textProperty()}); 

    oList.addListener((ListChangeListener.Change<? extends TextField> c) -> { 
     while (c.next()) { 
      if (c.wasUpdated()) { 
       for (int i = c.getFrom(); i < c.getTo(); ++i) { 
        System.out.println("Updated index: " + i + ", new value: " + c.getList().get(i).getText()); 
       } 
      } 
     } 
    }); 
1

我在想,我會將這個問題標記爲重複,因爲您有一個完全相似的問題here

但最後,您還想在偵聽器中引用TextField,所以我將添加一個答案。

該代碼段將10 TextField對象添加到ArrayList並向每個對象添加一個偵聽器。

for (int i = 0; i < 10; i++) { 
    TextField tf = new TextField(); 
    final int index = i; 
    tf.textProperty().addListener((obs, oldVal, newVal) -> { 
     System.out.println("Text of Textfield on index " + index + " changed from " + oldVal 
       + " to " + newVal); 
    }); 
    lfLetters.add(tf); 
} 

或者,如果你ArrayList已經被初始化,您可以簡單地iterate through它:

lfLetters.forEach(tf -> { 
    tf.textProperty().addListener((obs, oldVal, newVal) -> { 
     System.out.println("Text of Textfield on index " + lfLetters.indexOf(tf) + " changed from " + oldVal 
       + " to " + newVal); 
    }); 
}); 

樣本輸出

Text of Textfield on index 2 changed from InitialText - 2 to ModifiedText - 2 
Text of Textfield on index 6 changed from InitialText - 6 to ModifiedText - 6 
+0

注意,你可以更有效地訪問索引中的第一個例子= i;'在添加偵聽器之前。 –

+0

你是完全正確的,答案已更新。 – DVarga