- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我已经尝试了几个小时来解决这个问题,并且之前在这些论坛上已经得到了回答,但我真的很感激一些帮助,因为没有人真正专门解决我的问题或提出非常不同的解决方案,我不太确定是什么尝试(即使我已经尝试了所有这些,我敢说)。
问题是这样的:我有一个包含 6 个场景及其各自 Controller 的 JavaFX 应用程序。我有一个创建对象的 Person 类,我想将该对象存储在一个全局的 ArrayList 中(即,所有场景都可以访问),这样当我关闭应用程序时,我可以调用另一个方法将它保存到一个序列化的文件。
我实际上并没有在前几个场景中使用 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/
我是一名优秀的程序员,十分优秀!