2015-11-26 66 views
1

我试图按QuitMenuItemExit应用程序的方法。JavaFX不能在MenuItem上使用onAction

我有以下方法:

@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

你有FX:控制器属性,在FXML文件? –

+0

不,但我不明白为什么现在需要?我试图将其设置为crassname:Player,但它不起作用,没有找到它。 –

+1

需要解析“#doExit”,否则它甚至不会猜测在哪里查找;)。为Player提供完整的包路径,如fx:controller =“path.to.my.Player” –

回答

1

EDIT1的自营进出口经营权:好吧,我设法从Script ModeScene Builder切换到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(); 
+0

如果你添加一个属性到根元素,你也可以在fxml文件中指定控制器(参见[Uluk Biy的评论](http://stackoverflow.com/questions/33933003/javafx-cannot-use-onaction-on -menuitem#comment55627161_33933003))。在这种情况下,'FXMLLoader'会为你创建控制器(如果默认的构造函数是public的)[示例](https://docs.oracle.com/javase/8/javafx/fxml-tutorial/fxml_tutorial_intermediate.htm# CACBGIIG)。既然你不保留对控制器的引用,那也没关系......只是不要一次使用两种可能性 - 否则你会得到另一个错误。 – fabian

0

的OnAction接受接受动作事件作为参数的方法确保您提供具有动作事件作为论据

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> 
的方法

Java

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