我在按下Exit
Quit
时尝试为MenuItem
应用程序制作方法。
我有以下方法:
@FXML
public void doExit(ActionEvent event) {
Platform.exit();
System.exit(0);
}
我收到此错误:
javafx.fxml.LoadException: Error resolving onAction='doExit', either the event handler is not in the Namespace or there is an error in the script.
project/build/resources/main/Player.fxml:21
Player.fxml
的第21行是:
<MenuItem mnemonicParsing="false" onAction="doExit" text="Quit" />
我尝试删除/添加@FXML
表示法,该方法未定义为static
因此它应该可以正常导入ActionEvent
答案 0 :(得分:1)
Edit1:好的,我设法将Scene Builder
从Script Mode
切换到Method Mode
,这解决了问题,但现在我得到了:
javafx.fxml.LoadException: No controller specified.
project/build/resources/main/Player.fxml:21
<MenuItem mnemonicParsing="false" onAction="#doExit" text="Quit" />
Edit2:我设法以编程方式创建控制器,因为我没有任何包声明,我不想创建一个。
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Player.fxml"));
fxmlLoader.setController(new Player());
Parent root = (Parent)fxmlLoader.load();
答案 1 :(得分:0)
onAction 接受一个接受ActionEvent作为参数的方法,确保提供一个以ActionEvent作为参数的方法
实施例
<强> FXML 强>
<Menu mnemonicParsing="false" text="File">
<items>
<MenuItem mnemonicParsing="false" fx:id="action_backup" text="Backup" onAction="#performAction"/>
<MenuItem mnemonicParsing="false" fx:id="action_settings" text="Settings" onAction="#performAction"/>
</items>
</Menu>
<强>爪哇强>
public void performAction(ActionEvent actionEvent) {
//you can add this method for multiple menu item and identify
//each menu item by its id
MenuItem target = (MenuItem) actionEvent.getSource();
System.out.println("Clicked On Item:"+target.getId());
}