序列化 JavaFX 组件

Res*_*shi 7 java user-interface serialization javafx

我正在尝试在 Java FX 下开发一个小拖放应用程序。用户将在某些位置放置按钮、菜单、标签等 JFX 组件。完成后,他将保存此布局,稍后他将重新打开该布局并再次使用它。

存储有关在某个位置放置的所有对象的信息很重要。

为此,我决定使用序列化。但我无法序列化 JavaFX 组件。我尝试序列化按钮、场景、阶段、JFXPane,但似乎没有任何效果(我获得了 NotSerializableException)。

任何建议如何保存所有组件然后检索它们?

PS:我试图用 FXML 找出一些方法,但我没有成功。

非常感谢您的回答:)

Aga*_*ria 5

如果在服务器端保存用户组件的主要目标 - 是能够向用户显示相同的界面 - 为什么不保存有关用户组件所需的所有描述性信息,并且在需要时 - 只需重建用户界面再次,使用存储的描述性信息?这是原始示例:

/* That is the class for storing information, which you need from your components*/
 public class DropedComponentsCoordinates implements Serializable{
private String componentID;
private String x_coord;
private String y_coord;
//and so on, whatever you need to get from yor serializable objects;
//getters and setters are assumed but not typed here.
 }

 /* I assume a variant with using FXML. If you don't - the main idea does not change*/
 public class YourController implements Initializable {

List<DropedComponentsCoordinates> dropedComponentsCoordinates;

@Override
public void initialize(URL url, ResourceBundle rb) {
    dropedComponentsCoordinates = new ArrayList();
}

//This function will be fired, every time 
//a user has dropped a component on the place he/she wants
public void OnDropFired(ActionEvent event) {
    try {
        //getting the info we need from components
        String componentID = getComponentID(event);
        String component_xCoord = getComponent_xCoord(event);
        String component_yCoord = getComponent_yCoord(event);

        //putting this info to the list
        DropedComponentsCoordinates dcc = new DropedComponentsCoordinates();
        dcc.setX_Coord(component_xCoord);
        dcc.setY_Coord(component_yCoord);
        dcc.setComponentID(componentID);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

private String getComponentID(ActionEvent event){
    String componentID;
    /*getting cpmponentID*/
    return componentID;
}
private String getComponent_xCoord(ActionEvent event){
    String component_xCoord;
    /*getting component_xCoord*/
    return component_xCoord;
}
private String getComponent_yCoord(ActionEvent event){
    String component_yCoord;
    /*getting component_yCoord*/
    return component_yCoord;
}
}
Run Code Online (Sandbox Code Playgroud)


jew*_*sea 5

您是对的,JavaFX(从 2.1 开始)不支持使用 Java Serializable接口的组件序列化- 因此您不能使用该机制。

JavaFX 可以使用FXMLLoader.load()方法从 FXML 文档反序列化。

不过,诀窍是如何将现有组件和状态写入 FXML?

目前,执行 FXML 序列化的平台没有任何公开内容。显然,创建一个通用的场景图 => FXML 序列化器是一项相当复杂的任务(我所知道的没有公开的 3rd 方 API)。遍历场景图并为一组有限的组件和属性写出 FXML 不会太困难。