如何在 JavaFX 项目中使用 KeyEvent? [英] How to use KeyEvent in JavaFX project?
问题描述
我已经搜索了很长时间,以了解如何编写 KeyEvent
以允许通过 ENTER 键
单击我的 Button.请注意,我使用的是 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屋!