JavaFX不能在MenuItem上使用onAction

时间:2015-11-26 07:40:56

标签: java javafx scenebuilder

我在按下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

2 个答案:

答案 0 :(得分:1)

Edit1:好的,我设法将Scene BuilderScript 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()); 
}

As use by me in one of my project