我正在使用 Scene Builder 在 JavaFX 中开发入侵者游戏(我必须用大炮射击飞机),但我在 lambda 函数方面遇到了问题。
我确信代码是正确的,因为如果我通过场景生成器的选项(操作时)关联代码,它就可以工作,但是,当我尝试使用 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()
方法,该方法将执行以下操作:为以下操作事件分配一个监听器(通过 lambda) 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/