JavaFX从控制器获取场景 [英] JavaFX getting scene from a controller

查看:767
本文介绍了JavaFX从控制器获取场景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用Java FX,FXML和场景构建器,并且我一直在尝试将关键侦听器添加到场景的一个控制器中.但是,当我执行此操作时,关键的侦听器无法正常工作,我认为这是因为他们没有将注意力集中在特定的场景上.我试图访问该控制器所在的场景以直接对其进行设置,但事实证明它是空场景的一部分.

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.

是否有一种方法可以访问该控制器用于尝试将关键事件和侦听器分配给该特定场景的场景?我应该遍历整个应用程序是静态的rootController吗?或者,更好的是,有没有更简单的方法可以解决此问题?

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?

我看到的大多数示例都假定所有东西都大部分集中在一个主类中,或者在不引入FXML的情况下在其他几个类中分开,并且我不确定在拥有Java控制器FXML时如何应用它们的修补程序页和主应用程序都分开了.

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.

感谢您的帮助!

推荐答案

使用Controller中绑定的任何控件并使用

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

请记住不要在

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

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
    }

}

这篇关于JavaFX从控制器获取场景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆