[英]JavaFX TextField listener
我需要協助。 我有一個Textfield
的ArrayList
。
static List<TextField> lfLetters = new ArrayList<>();
我想檢查值是否已更改。 如果是這樣,我想知道它是哪個文本字段。 我知道我可以用一個監聽器做到這一點,但這只適用於一個人。
TextField textField = new TextField();
textField.textProperty().addListener((observable, oldValue, newValue) -> {
System.out.println("textfield changed from " + oldValue + " to " + newValue);
});
我想讓它在數組上工作並確定哪個文本字段已更改。
提前致謝!
您可以將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());
}
}
}
});
我想我會把這個問題標記為副本,因為你在這里有一個完全相似的問題。
但最后,您希望在偵聽器中也引用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
已經初始化,您可以簡單地遍歷它:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.