【问题标题】:Menu item not cast node javafx scene菜单项未投射节点 javafx 场景
【发布时间】:2018-01-14 18:32:06
【问题描述】:

我正在制作一个 JavaFX 应用程序。我创建了一个 Menuitem About。单击关于菜单项后,它将显示一个新窗口,其中包含有关我的应用程序的一些信息。该窗口是带有自定义关闭按钮的Anchor Pane。我已经在运行时设置了底层涂层。我想在不关闭主应用程序的情况下关闭此窗口。我不想在方法调用时将其可见性关闭。我在网络中看到了一些解决方案,例如Window existingWindow = ((Node) event.getSource()).getScene().getWindow();,但我无法使用它,因为我遇到了类似于此 Menu item not cast node javafx scene 的错误。我怎样才能实现这个目标?

【问题讨论】:

  • 没有其他节点可以获取窗口吗?
  • 不,我想从关于 menuitem 中获得它,否则我必须在按钮单击时设置此功能。
  • 不确定我是否理解。同一个窗口中肯定还有其他节点吗?你能在问题中加入一些代码来显示你在做什么吗?
  • 我不明白你的意思。对不起。单击菜单项 about 时,我得到 about 窗口。关于窗口有四个标签和一个按钮。我想在不关闭主应用程序的情况下关闭它。
  • 好的,所以您只需调用aboutWindow.hide(),其中aboutWindow 是对试图关闭的窗口的引用。您可以使用label.getScene().getWindow()button.getScene().getWindow() 获得该引用,其中labelbutton 是窗口中显示的节点。有什么问题?

标签: javafx-8


【解决方案1】:

其实这不是我自己的答案,但我设法理解了@James_D。我通常创建来管理打开的窗口,否则我必须编写很多代码这是解决方案代码。 在您的控制器类中:

@FXML
void openAnotherWindow(ActionEvent actionEvent) {
    try {
        OpenWindow.openWindowMenuItem(someLabel, "views/some.fxml", "Title", 600, 400,
                false, "resources/pictures/some_icon.png");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

还有 OpenWindow 类

public class OpenWindow {
public static void openWindowMenuItem(Node label, String recource, String title,
                                      int width, int height, boolean resizeable, String icon) throws IOException {
    Parent root = FXMLLoader.load(Objects.requireNonNull(OpenWindow.class.getClassLoader().getResource(recource)));
    Stage stage = new Stage();
    Scene scene = new Scene(root, width, height);
    if (icon != null) {
        stage.getIcons().add(new Image(icon));
    }
    stage.setTitle(title);
    stage.setResizable(resizeable);
    stage.setScene(scene);
    stage.show();

    // close current window
    label.getScene().getWindow().hide(); // this is key point
}
}

你可以在没有额外课程的情况下完成它。希望它会有所帮助,再次感谢@James_D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多