如何在场景图的节点中监听WindowEvent.WINDOW_SHOWN?


一生流水
2025-03-18 02:08:52 (21天前)
  1. 似乎WindowEvent.WINDOW_SHOWN永远不会在其中的任何节点上调度


现场
</跨度>
无论如何(我能找到)也不知道节点何时可见/呈现/显示。例如……(阶段阶段)抛出异常
{
Parent root = FXMLLoader.load(TestController.class.getResource(“TestView.fxml”));


现场
</跨度>

现场
</跨度>
=新的

现场
</跨度>
(根);
stage.setScene(

现场
</跨度>

3 条回复
  1. 0# 不丶离 | 2019-08-31 10-32



    我想其中一个可能的解决方案是添加以下方法

    TestController.java




    1. public void handleWindowShownEvent()
      {
      usernameInput.requestFocus();
      }

    2. </code>


    然后改变

    start

    方法

    TestLauncher

    以下内容:




    1. @Override
      public void start(Stage stage) throws Exception
      {
      FXMLLoader loader = new FXMLLoader();
      Parent root = (Parent)loader.load(TestController.class.getResourceAsStream(“TestView.fxml”));
      final TestController controller = (TestController)loader.getController();
      stage.addEventHandler(WindowEvent.WINDOW_SHOWN, new EventHandler()
      {
      @Override
      public void handle(WindowEvent window)
      {
      controller.handleWindowShownEvent();
      }
      });
      Scene scene = new Scene(root);
      stage.setScene(scene);
      stage.show();
      }

    2. </code>


    我真的很欢迎其他解决方案,因为这个看起来太笨重……


  2. 1# 滔滔江水 | 2019-08-31 10-32



    另一个解决方案当然不是很性感但是将节点与应用程序分离:




    1. root.sceneProperty().addListener(new ChangeListener() {
      @Override
      public void changed(ObservableValue<? extends Scene> observable, Scene oldValue, Scene newValue) {
      newValue.windowProperty().addListener(new ChangeListener() {
      @Override
      public void changed(ObservableValue<? extends Window> observable, Window oldValue, Window newValue) {
      newValue.addEventHandler(WindowEvent.WINDOW_SHOWN, new EventHandler() {
      @Override
      public void handle(WindowEvent event) {
      usernameInput.requestFocus();
      }
      });
      }
      });
      }
      });

    2. </code>


    在我的情况下更有意义。


登录 后才能参与评论