我无法让我的javafx项目响应键盘事件。我想左右移动矩形以响应箭头键。我在fxml中注册了控制器类,并在矩形中注册了处理事件。这是我的三个班级:
这是主要的
Comaparator
这是控制器:
select id, name, lateral view explode(info) from info_table
这是fxml:
package application;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
String fxmlResource = "/application/SpaceUniverse4.1.fxml";
Parent panel;
panel = FXMLLoader.load(getClass().getResource(fxmlResource));
//MissionControl controller = new MissionControl();
Scene scene = new Scene(panel);
primaryStage.setScene(scene);
primaryStage.show();
//panel.requestFocus();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
答案 0 :(得分:0)
将您的handle方法更改为此原因是您不能多次移动它的原因是您使用的.getX()返回0,这对我来说是个好运气
@FXML
void handleKeyboardInput(KeyEvent event) {
int currentX = (int) ship.getLayoutX();
if (event.getCode() == KeyCode.LEFT && ship.getLayoutX() >= 14) {
currentX = currentX - 5;
ship.setLayoutX(currentX);
} else if (event.getCode() == KeyCode.RIGHT && ship.getLayoutX() <= 500) {
currentX = currentX + 5;
ship.setLayoutX(currentX);
}
}
如果您想在整个屏幕上接受按键输入,请使用此
universe.getParent().getScene().setOnKeyPressed(this::handleKeyboardInput);