gpt4 book ai didi

java - 如何在 JavaFX 2 中将 ArrayList 从一个场景传递到另一个场景?

转载 作者:行者123 更新时间:2023-11-30 09:10:39 36 4
gpt4 key购买 nike

所以我已经尝试了几个小时来解决这个问题,并且之前在这些论坛上已经得到了回答,但我真的很感激一些帮助,因为没有人真正专门解决我的问题或提出非常不同的解决方案,我不太确定是什么尝试(即使我已经尝试了所有这些,我敢说)。

问题是这样的:我有一个包含 6 个场景及其各自 Controller 的 JavaFX 应用程序。我有一个创建对象的 Person 类,我想将该对象存储在一个全局的 ArrayList 中(即,所有场景都可以访问),这样当我关闭应用程序时,我可以调用另一个方法将它保存到一个序列化的文件。

我实际上并没有在前几个场景中使用 ArrayList,因为它们是菜单,所以创建对象的实际方法直到第三个场景左右才运行。

我已经成功创建了场景,我可以在它们之间切换,我只是不知道

  1. 在哪里声明 ArrayList(如果在 main 方法中,主类还是在哪里?)
  2. 如何在场景之间传递这个 ArrayList,以便他们都能够访问它们。

我目前使用这个类在场景之间切换:

public class SelectScene  {
public void setScene(String fxmlFileName, String title, ActionEvent event) throws IOException{
Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
Parent root = FXMLLoader.load(getClass().getResource(fxmlFileName));
Scene scene = new Scene(root);
scene.getStylesheets().add(FinalDossier.class.getResource("style.css").toExternalForm());
stage.setTitle(title);
stage.setScene(scene);
}

我感谢任何帮助:)

最佳答案

有几种方法可以做到这一点:基本上所有方法都涉及不使用静态 FXMLLoader.load(URL) 方法,而是创建一个 FXMLLoader 实例。

一种方法是在您的代码中创建 Controller ,使用共享列表初始化它们,然后将它们传递给 setController(...)。在此版本中,您将从 FXML 文件中删除 fx:controller 属性。

不过,在您的情况下,似乎更好的方法是为 FXMLLoader 定义一个 Controller 工厂。这是一个对象,它告诉 FXMLLoader 如何从 fx:controller 属性中定义的类名中获取实例。这只涉及一点反射魔法。所以你会做类似的事情

public class SelectScene  {


private Callback<Class<?>, Object> controllerFactory ;

public SelectScene(final List<...> data) {
controllerFactory = new Callback<Class<?>, Object>() {
@Override
public Object call(Class<?> type) {
try {
Constructor<?> constructor = type.getDeclaredConstructor(List.class);
return constructor.newInstance(data);
} catch (NoSuchMethodException exc) {
return type.newInstance();
} catch (Exception ex) {
// trouble...
ex.printStackTrace();
return null ;
}
}
};
}

public void setScene(String fxmlFileName, String title, ActionEvent event) throws IOException{
Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlFileName));
loader.setControllerFactory(controllerFactory);
Parent root = (Parent)loader.load();
Scene scene = new Scene(root);
scene.getStylesheets().add(FinalDossier.class.getResource("style.css").toExternalForm());
stage.setTitle(title);
stage.setScene(scene);
}
}

对于需要访问共享数据的 Controller ,只需定义一个参数为List的构造函数:

public class MyController {
private final List<...> data ;
public MyController(List<...> data) {
this.data = data ;
}
public void initialize() {
// usual initialize method
}
}

对于没有该构造函数的 Controller , Controller 工厂将回退到默认构造函数。

您可以在任何方便的地方定义 List:直接在 SelectScene 类中(如代码所示),或者您可以更早地定义它(例如,在您的 start() 方法中),然后将它传递给 SelectScene 构造函数.这仅取决于您可能还需要访问它的其他位置。

更新:完整示例 here

关于java - 如何在 JavaFX 2 中将 ArrayList 从一个场景传递到另一个场景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22448331/

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