[英]firing a click event when pressing enter inside a textfield
sorry for the questions... but I'm a little stuck again.很抱歉这些问题......但我又有点卡住了。
I ask these questions so I can get the most out of my time/learning.我问这些问题是为了最大限度地利用我的时间/学习。
I am trying to fire a click event (so when i manually click the login btn) with the enter key.我试图用回车键触发点击事件(所以当我手动点击登录 btn 时)。
The code i have so far我到目前为止的代码
code代码
usernameField.setOnKeyPressed((KeyEvent event) -> {
if(event.getCode()==KeyCode.ENTER){
loginBtn.fire();
System.out.println("Worked");
}
});
That does what it's supposed to, almost.这几乎完成了它应该做的事情。 the system out message appears but does now fire the loginBtn.
出现系统输出消息,但现在确实触发了 loginBtn。
I am using JavaFX and JFXButtons/textboxes if that makes a difference如果这有所不同,我正在使用 JavaFX 和 JFXButtons/textboxes
Text fields fire action events when the user presses the enter key.当用户按下回车键时,文本字段会触发动作事件。 So all you need is
所以你只需要
EventHandler<ActionEvent> loginHandler = e -> {
// handle login here...
};
usernameTextField.setOnAction(loginHandler);
loginBtn.setOnAction(loginHandler);
Or, if you prefer;或者,如果您愿意;
usernameTextField.setOnAction(e -> handleLogin());
loginBtn.setOnAction(e -> handleLogin());
// ...
private void handleLogin() {
// handle login here...
}
If you are using FXML, you can just map both onAction
handlers to the same controller method:如果您使用 FXML,您可以将两个
onAction
处理程序映射到相同的控制器方法:
<TextField fx:id="usernameTextField" onAction="#login" />
<Button fx:id="loginBtn" text="Log In" onAction="#login" />
and then in the controller然后在控制器中
public class Controller {
// ...
@FXML
private void login() {
// login action here..
}
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.