问题描述
我在我的字段上应用了侦听器
:
I have a listener
applied to my field:
nameTextField.addEventHandler(KeyEvent.KEY_TYPED, fieldChangeListener(50));
事件处理程序:
private EventHandler<KeyEvent> fieldChangeListener(final Integer max_Lengh) {
return new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
TextField field = (TextField) event.getSource();
String text = field.getText();
// I need here something like:
if(KeyEvent.VK_ENTER){
// do special part for ENTER KEY
}
}
}
}
问题是 KeyEvent事件
来自 javafx.scene.input.KeyEvent
和 KeyEvent.VK_ENTER
来自 com.sun .glass.events.KeyEvent
。我不知道如何确定ENTER键是否触发了 KEY_TYPED
事件。
Problem is KeyEvent event
is from javafx.scene.input.KeyEvent
and KeyEvent.VK_ENTER
from com.sun.glass.events.KeyEvent
. I don't know how can I determine if ENTER key triggered KEY_TYPED
event.
推荐答案
如果要在更改文本时进行输入验证,可以在 TextField $的
textProperty
上使用侦听器c $ c>:
If you want to do input validation when the text is changing, you could use a listener on the textProperty
of the TextField
:
textField.textProperty().addListener((observable, oldValue, newValue) ->
System.out.println("Input Validation"));
要检测何时按下,可以使用 onActionProperty
To detect when is pressed, you can use the onActionProperty
textField.setOnAction(event -> System.out.println("Enter pressed: Word Check"));
如果要防止用户输入字符失败了验证逻辑,然后可以使用 TextFormatter
(而不是听textProperty˙
)(此 TextField
仅接受整数):
If you want to prevent the user to input characters that fails the validation logic, then rather than listening to the textProperty˙
, you can use a TextFormatter
(this TextField
only accept integers):
textField.setTextFormatter(new TextFormatter<>(change ->
(change.getControlNewText().matches("([1-9][0-9]*)?")) ? change : null));
这篇关于JavaFX TextField文本验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!