当 TextField 中的文本更改时如何获取事件? JavaFX
How get an event when text in a TextField changes? JavaFX
每当 TextField 的文本发生更改时,如何生成新事件来处理?
使用 TextField
s textProperty
:
注册监听器
textField.textProperty().addListener((obs, oldText, newText) -> {
System.out.println("Text changed from "+oldText+" to "+newText);
// ...
});
或者使用ChangeListener
界面。
textField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable,
String oldValue, String newValue) {
System.out.println(" Text Changed to " + newValue + ")\n");
}
});
我的解决方案:
....
String temp;
....
//previously in some method when starting to take initial value of the textfield and save it in a temporal
temp=id_textfield.getText();
....
//when losing focus we check if the new value is different
id_textfield.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
//focus in
if (newValue) {
temp = id_textfield.getText();
}
//focus out
if (oldValue) {
if (!(temp.equals(id_textfield.getText()))) {
System.out.println("New String")
}
}
}
});
每当 TextField 的文本发生更改时,如何生成新事件来处理?
使用 TextField
s textProperty
:
textField.textProperty().addListener((obs, oldText, newText) -> {
System.out.println("Text changed from "+oldText+" to "+newText);
// ...
});
或者使用ChangeListener
界面。
textField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable,
String oldValue, String newValue) {
System.out.println(" Text Changed to " + newValue + ")\n");
}
});
我的解决方案:
....
String temp;
....
//previously in some method when starting to take initial value of the textfield and save it in a temporal
temp=id_textfield.getText();
....
//when losing focus we check if the new value is different
id_textfield.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
//focus in
if (newValue) {
temp = id_textfield.getText();
}
//focus out
if (oldValue) {
if (!(temp.equals(id_textfield.getText()))) {
System.out.println("New String")
}
}
}
});