我有一个 JavaFX 应用程序。我有一个按钮,单击该按钮会调用一个操作并加载另一个 fxml 文件。这非常有效。
我决定将此功能放在应用程序的菜单中。
因此,我创建了一个菜单,并从场景构建器中添加了菜单项。我正确分配了“操作时”事件,就像我对其他按钮所做的那样。但是,当我点击时出现以下错误:
Glass detected outstanding Java exception at -[GlassViewDelegate sendJavaMouseEvent:]:src/com/sun/mat/ui/GlassViewDelegate.m:541
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
Caused by: java.lang.ClassCastException: javafx.scene.control.MenuItem cannot be cast to javafx.scene.Node
at plataformavalidezpredictiva.MainController.handleAction(MainController.java:60)
... 38 more
这是处理程序的代码。再说一遍,这适用于我放置在 UI 中的按钮,但在菜单栏中不起作用:
public void handleAction(ActionEvent event) throws Exception{
Node node = (Node)event.getSource();
Stage stage=(Stage) node.getScene().getWindow();
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml/GUIFile.fxml"));
Parent root = (Parent)fxmlLoader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
似乎给我带来问题的行是:
Node node = (Node)event.getSource();
有什么想法吗?
编辑:我在这里看到了帖子Unable to get Scene from MenuItem in JavaFX但这对我不起作用,因为它没有找到菜单栏的 getScene() 方法。
最佳答案
将一些节点(例如MenuBar
,但它实际上可以是同一场景中的任何节点)注入(inject)到 Controller 中。在该节点上调用 getScene()
并在场景上调用 getWindow()
。
例如
Main.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuItem?>
<BorderPane xmlns:fx="http://javafx.com/fxml" fx:controller="exitfrommenu.MainController">
<top>
<MenuBar fx:id="menuBar">
<Menu text="File">
<MenuItem text="Exit" onAction="#exit"/>
</Menu>
</MenuBar>
</top>
</BorderPane>
MainController.java
package exitfrommenu;
import javafx.fxml.FXML;
import javafx.scene.control.MenuBar;
public class MainController {
@FXML
private MenuBar menuBar ;
@FXML
private void exit() {
Stage stage = (Stage) menuBar.getScene().getWindow() ;
// This exits the application, but of course you can do anything
// you like with the stage, such as showing a new scene in it:
stage.hide();
}
}
Main.java
package exitfrommenu;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.fxml.FXMLLoader;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = (BorderPane)FXMLLoader.load(getClass().getResource("Main.fxml"));
Scene scene = new Scene(root,400,400);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
关于java - 使用JavaFX的MenuBar会导致 'Glass detected outstanding Java exception',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22887170/