gpt4 book ai didi

JavaFX通过initialize方法实现Post render事件

转载 作者:行者123 更新时间:2023-11-30 03:50:40 26 4
gpt4 key购买 nike

执行初始化方法后,我需要立即用一些文本消息更新 Controller 。这意味着 UI 的发布(由于用户需要看到出现此消息)。我见过类似帖子 Post render event in JavaFX 的一些解决方案, How to listen for WindowEvent.WINDOW_SHOWN 。但似乎我无法用这些解决方案完成我的任务。

作为解决方案当我按以下方式使用 WindowEvent.WINDOW_SHOWN 时,它将尝试执行我已声明的事件处理程序位置(在应用程序的早期阶段),这意味着当舞台初始化时(执行应用程序的start(Stage stage)) 然后我得到了一些空指针异常。我的应用程序有许多 Controller ,我需要在某些 UI 流程的中间进行此操作。一旦执行特定 Controller 的初始化方法(在渲染后阶段),如何完成此任务。谢谢。

@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<WindowEvent>()
{
@Override
public void handle(WindowEvent window)
{
controller.handleWindowShownEvent();
}
}
});
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}

如下在我的应用程序中当我添加事件处理程序并使用 Spring Context 加载相关 Controller 时,它将产生空指针异常。

通过handleWindowShowEvent方法,我使用了我声明的所有UI组件和资源包。当该方法要执行时,它将通过这些 UI Controller 和资源包调用生成空指针异常。

问题是,由于 UI 尚未渲染,初始化 block 似乎尚未执行,但 handleWindowShowEvent 方法将使用那些未初始化的组件。

添加事件处理程序

  stage.addEventHandler(WindowEvent.WINDOW_SHOWN, new EventHandler<WindowEvent>() {

@Override
public void handle(WindowEvent window) {

Platform.runLater(new Runnable() {
@Override
public void run() {

try {

// Load Controller with Spring Context
EquipmentConfigProcessController eqConfProcessController
= ComponentUtil.appContext.getBean(EquipmentConfigProcessController.class);

eqConfProcessController.handleWindowShowEvent();

} catch (Exception e) {
logger.error("Exception while going to execute handleWindowShowEvent method on " +
"EquipmentConfigProcessController [" + e.getMessage() + "]");
}
}
});
}
});

初始化方法

      private ResourceBundle rb;
@FXML private Pane detailPane;
@FXML private HBox detailBox;
@FXML public Label devNameLbl;

@Override
public void initialize(URL url, ResourceBundle rb) {

// Initialise resource bundle
this.rb = rb;
}

handleWindowShowEvent方法

   public void handleWindowShowEvent() {

// Null Pointer Exception occurred with Resource ResourceBundle
Label updateMessage = new Label(rb.getString("equipment.message"));

// Null Pointer Exception occurred with detailBox invocation
detailBox.getChildren().clear();

// More codes
}

最佳答案

尝试为

stage.addEventHandler(WindowEvent.WINDOW_SHOWN, new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent window) {
Platform.runLater(new Runnable() {
@Override
public void run() {
controller.handleWindowShownEvent();
}
});
}
});

关于JavaFX通过initialize方法实现Post render事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24551803/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com