如何在JavaFX项目中使用KeyEvent? [英] How to use KeyEvent in JavaFX project?
问题描述
我已经搜索了很长时间,如何编写 KeyEvent
以允许按下按钮 ENTER键
。请注意,我使用的是JavaFX和 FXML
文件。
I have searched for a long time for how to write a KeyEvent
to allow my Button clicks by ENTER key
. Note that I'm using JavaFX and FXML
files.
问题是,当在FXML文件的onKeyTyped文本字段中设置时,FXML文件不接受它。它说找不到句柄方法
。它只接受 ActionEvent
方法,所以我尝试了这段代码:
The problem is that when set in the onKeyTyped text field in the FXML file, the FXML Files doesn't accept it. It says Handle method not found
. It just accept ActionEvent
method so I have tried this code:
@FXML
private void key (KeyEvent evt) throws IOException{
if (evt.getCode() == KeyEvent.VK_ENTER){
String az = text1.getText();
//c.1
if(az.contains("1")){
String hh = text11.getText();
Socket socket = null;
InetSocketAddress isa = new InetSocketAddress (hh,80);
}
}
}
所以请任何人帮助我?
推荐答案
您的代码存在一些问题:
You have few issues with your code :
-
您使用
onKeyTyped
而不是onKeyPressed
。有关详细信息,请访问此链接
You are using
onKeyTyped
instead ofonKeyPressed
. For more information visit this link
您最有可能使用 java.awt.event.KeyEvent
,它不适用于 JavaFX事件
。尝试使用 javafx.scene .input.KeyEvent
。
You are most probably using java.awt.event.KeyEvent
, which will not work with JavaFX events
. Try to use javafx.scene.input.KeyEvent
.
我得出这个结论的原因是因为JavaFX不支持 KeyEvent.VK_ENTER
而是 KeyCode.ENTER
The reason I came to this conclusion is because JavaFX doesn't support KeyEvent.VK_ENTER
but instead have KeyCode.ENTER
一个具体的例子如下所示,您可以使用相同的方法将其转换为FXML:
A concrete example is shown below, you can use the same to convert it into FXML:
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class ButtonExample extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane pane = new BorderPane();
Button button = new Button("Press Me!");
pane.setCenter(button);
Scene scene = new Scene(pane, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
button.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
System.out.println("Enter Pressed");
}
}
});
}
public static void main(String[] args) {
launch(args);
}
}
这篇关于如何在JavaFX项目中使用KeyEvent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!