简体   繁体   English

JavaFX从控制器获取场景

[英]JavaFX getting scene from a controller

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. 我最近开始玩Java FX,FXML和场景构建器,我一直在尝试将关键监听器添加到场景的一个控制器中。 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. 我试图访问控制器所属的场景,以便直接设置它,但它出现了它是空场景的一部分。

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? 我应该通过整个应用程序中的静态rootController吗? Or, better yet, is there a simpler way of going about this? 或者,更好的是,有更简单的方法来解决这个问题吗?

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! 谢谢你的帮助!

Use any of the controls that is bound in the Controller and use getScene() on it. 使用Controller中绑定的任何控件并对其使用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
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM