2012-06-14 23 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