[英]Run same function when clicking and pressing enter key
I have this function that runs when clicking on a button, but I want to run the same function when pressing enter. 我具有在单击按钮时运行的功能,但是我想在按Enter键时运行相同的功能。 How should I do this?
我应该怎么做?
@FXML
public void login(ActionEvent event) throws IOException {
if(txtUName.getText().equals("jesse") && txtPass.getText().equals("essej")){
Parent home;
try {
home = FXMLLoader.load(getClass().getResource("Home.fxml"));
Scene homeScene = new Scene(home);
Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();
window.setScene(homeScene);
window.show();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else {
lblError.setVisible(true);
}
}
You need a key event, this event should then be check it is "enter" which was pushed. 您需要一个关键事件,然后应检查该事件是否已被“输入”。
You mean you have another @FXML function that you want to do the same? 您的意思是您还有另一个想要执行相同操作的@FXML函数? Just put your logic in a separate function and call it from your event functions.
只需将逻辑放在单独的函数中,然后从事件函数中调用它即可。
@FXML
public void buttonPressed(MouseEvent event) {
doSomething(event);
}
@FXML
public void keyPressed(KeyEvent event) {
doSomething(event);
}
private void doSomething(InputEvent event) {
// your code here
}
This KeyEvent and MouseEvent inherit from InputEvent . 此KeyEvent和MouseEvent继承自InputEvent 。 You can still call
.getSource()
because it's inherited and in the code you've shown there is nothing more specific you do with the event. 您仍然可以调用
.getSource()
因为它是继承的,并且在您显示的代码中,您没有对事件进行更具体的处理。
I found a working solution for me. 我为我找到了一个可行的解决方案。
You can set the button as a Default Button in Scene Builder so when you press enter it also activates the method. 您可以在Scene Builder中将按钮设置为“默认按钮”,因此当您按Enter时,它也会激活该方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.