gpt4 book ai didi

java - 在 JavaFX8 中使用 FXML 的 Lambda 函数

转载 作者:行者123 更新时间:2023-11-30 08:36:25 24 4
gpt4 key购买 nike

我正在使用 Scene Builder 在 JavaFX 中开发一款入侵者游戏(我必须用大炮射击飞机)但是我遇到了 lambda 函数的问题。

我确定代码是正确的,因为如果我通过 Scene Builder 的选项(On action)关联代码,它就可以工作,但是,当我尝试使用 lambda 函数时,我无法更改我的场景。我哪里错了?

public class SchermataGiocoController {

private Parent Menu, Avvio;
private TranslateTransition tt;
private Cannone cannone; //cannone = cannon
private Aereo aereo; //aereo = plane
private Proiettile proiettile; //proiettile = bullet
private RotateTransition rt;

@FXML
private Button down;

@FXML
private Circle circle;

@FXML
private Button su;

@FXML
private Button exit;

@FXML
private ImageView cannone_im;

@FXML
private AnchorPane SchermataGioco;

@FXML
private ImageView aereo_im;

@FXML
private Button menu;

@FXML
private Button home;

@FXML
void initialize() {
assert exit != null : "fx:id=\"exit\" was not injected: check your FXML file 'SchermataGioco.fxml'.";
assert cannone_im != null : "fx:id=\"cannone_im\" was not injected: check your FXML file 'SchermataGioco.fxml'.";
assert su != null : "fx:id=\"su\" was not injected: check your FXML file 'SchermataGioco.fxml'.";
assert SchermataGioco != null : "fx:id=\"SchermataGioco\" was not injected: check your FXML file 'SchermataGioco.fxml'.";
assert aereo_im != null : "fx:id=\"aereo_im\" was not injected: check your FXML file 'SchermataGioco.fxml'.";
assert menu != null : "fx:id=\"menu\" was not injected: check your FXML file 'SchermataGioco.fxml'.";
assert down != null : "fx:id=\"down\" was not injected: check your FXML file 'SchermataGioco.fxml'.";
assert home != null : "fx:id=\"home\" was not injected: check your FXML file 'SchermataGioco.fxml'.";
cannone = new Cannone(141, 104, 14, 362);
proiettile = new Proiettile(16, 16, 14, 362);
TranslateTransition();
}


@FXML
public void vaiMenu() {
menu.setOnAction((ActionEvent event) -> {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Game.class.getResource("/game/view/Menu.fxml"));
Menu = (Parent) loader.load();
menu.getScene().getWindow().hide();
} catch (IOException ioe) {
ioe.getMessage();
}
Stage stage = new Stage();
stage.setScene(new Scene(Menu));
stage.show();
});
}

最佳答案

如果您将 vaiMenu()SceneBuilder 中的“On Action”相关联,那么(如预期的那样),例如当点击 Button 时,vaiMenu() 方法将被执行,它只会做:为Button,因此它永远不会被执行,只是一次又一次地添加。

如果你想通过 SceneBuilder 分配监听器,比如:

<Button fx:id="menu" onAction="#vaiMenu" />

您不能使用 lambda(匿名函数),因为您需要在 FXML 文件中引用一个命名函数(在 onAction 属性中)。

如果您将当前的 lambda 插入到例如 Controller 的 initialize() 方法,它将正常工作,但在这种情况下,您不应在 FXML 文件中定义此属性。

关于java - 在 JavaFX8 中使用 FXML 的 Lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37791698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com