2012-06-14 85 views
3

我试图在Java FX下开发一点点拖拽&拖放应用程序。用户将在某些位置放置JFX组件,如按钮,菜单,标签。完成后,他将保存这个布局,之后他将重新打开布局,他将再次使用它。序列化JavaFX组件

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

我决定为此使用序列化。但是我无法序列化JavaFX组件。我试图序列化按钮,场景,阶段,JFXPane,但似乎没有工作(我获得了NotSerializableException)。

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

P.S .:我试图找出一些FXML的方法,但我没有成功。

非常感谢你对你的答案:)

回答

3

如果在服务器端保存用户组件的主要目标 - 是有可能表现出同样的接口给用户 - 为什么不保存所有描述您需要的关于用户组件的信息以及何时需要 - 只需使用存储的描述性信息重新构建用户界面?这里是原始的例子:

/* 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; 
} 
} 
+0

非常感谢您的回答。我正在考虑这样的策略,但我仍然想知道网络上是否出现了自动的东西。并没有像jewelsea发布。所以最后我个人会使用这个解决方案:) – Reshi

4

你是正确的,JavaFX的(如2.1)不支持使用Java Serializable界面组件的序列化 - 这样你就不能使用该机制。

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

但是,诀窍是如何编写现有的组件并指出FXML?

有一个序列化为FXML的forum discussion

目前,执行FXML序列化的平台没有任何公开内容。显然,创建一个通用的scenegraph => FXML序列化器是一项相当复杂的任务(并且,我没有公开第三方API)。迭代场景图并写出FXML以获取一组有限的组件和属性并不困难。

+1

以及同事张贴在这里。有一种解决方案来创建我可以序列化的对象。另一方面,从我的代码创建FXML。在我的项目中,创建FXML的复杂度可能会稍微高一点,但通过为具体组件标识注释@FXML,然后恢复整个场景会更加容易。 AsI必须快速开发它,我将使用他的解决方案。但我也将学习FXML的创建。因为对于其他人我认为它更自动。 – Reshi

+0

您是否看到过一些计划将这个功能(直接从源代码创建FXML)集成到JavaFX的标准库中? – Reshi

+0

不,我认为不太可能将这样的功能添加到JavaFX标准库中。 – jewelsea