JavaFX 从控制器获取场景

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26060859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:46:52  来源:igfitidea点击:

JavaFX getting scene from a controller

javajavafx-2keylistenerscenebuilder

提问by Keanu

I recently started playing around with Java FX, FXML, and scene builder, and I've been trying to add key listeners to one of the controllers for a scene. When I do this though, the key listeners don't work as they should, and I figure it's because they're not focused onto that particular scene. I tried to get access to the scene the controller was part of in order to set it directly, but it comes up that it's part of a null scene.

我最近开始尝试使用 Java FX、FXML 和场景构建器,并且我一直在尝试将关键侦听器添加到场景的控制器之一。但是,当我这样做时,主要听众并没有像他们应该的那样工作,我认为这是因为他们没有专注于那个特定的场景。我试图访问控制器所在的场景以直接设置它,但结果发现它是空场景的一部分。

Is there a way to gain access to the scene that this controller is used in in order to try and assign key event and listeners to that particular scene? Should I go through the rootController which is static throughout the whole application? Or, better yet, is there a simpler way of going about this?

有没有办法访问使用此控制器的场景,以便尝试将关键事件和侦听器分配给该特定场景?我应该通过整个应用程序中静态的 rootController 吗?或者,更好的是,有没有更简单的方法来解决这个问题?

Most examples I see assume that everything is mostly together in a main class or separated amongst a couple of other classes without FXML being brought in, and I'm not sure how to apply their fixes when I have the java controllers, FXML pages, and the main application all separated.

我看到的大多数示例都假设所有内容大部分都在一个主类中,或者在没有引入 FXML 的情况下与其他几个类分开,并且当我拥有 Java 控制器、FXML 页面和主应用程序全部分离。

Thanks for any help!

谢谢你的帮助!

采纳答案by ItachiUchiha

Use any of the controls that is bound in the Controller and use getScene()on it.

使用控制器中绑定的任何控件并getScene()在其上使用。

Remember not to use it in initialize()as the root element(though completely processed) is still not placed on the scene when initialize()is called for the controller

记住不要使用它,initialize()因为当initialize()为控制器调用时,根元素(尽管已完全处理)仍未放置在场景中

public class WindowMainController implements Initializable {

    @FXML
    private Button button;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        System.out.println(button.getScene()); // Gives you the Scene
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        System.out.println(button.getScene()); // Prints null
    }

}