如何序列化具有ObservableList的对象?

时间:2017-02-17 23:33:08

标签: java serialization javafx fxml observablelist

我实际上想要序列化一个对象列表,但我认为这没有区别。 我正在上课,只有两个属性。一个字符串和一个ObservableList。我将在其中包含序列化方法。我知道ObservableList没有实现可序列化,但我用它们填充了TableView,这就是我使用它的原因,但是如果有另一种方式,我对它开放。

public class Tratamiento implements Serializable{

private String name;
private ObservableList<Material> materials;

public Tratamiento(String name, ObservableList<Material> materials) {
    this.name= name;
    this.materials= materials;
}

public Treatment(){        
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name= name;
}

public ObservableList getMaterials() {
    return materials;
}

public void setMaterials(ObservableList materials) {
    this.materials = materials;
}


public int addTreatment(List tratamiento) {
    int res = 0; //Failure

    try {
        FileOutputStream fileOut = new FileOutputStream("Treatment.ser");
        ObjectOutputStream out = new ObjectOutputStream(fileOut);
        out.writeObject(treatment);
        out.close();
        fileOut.close();
        System.out.printf("Object has been serialized");
        res = 1;
    } catch (IOException i) {
        i.printStackTrace();

    }

    return res;
}



public List consultListTreatments() {
    int res = 0;
    //Deserialize file
    List<Treatment> list = new ArrayList<Treatment>();

    try {
        FileInputStream fileIn = new FileInputStream("Treatment.ser");
        ObjectInputStream in = new ObjectInputStream(fileIn);
        list = (List) in.readObject();     
        in.close();
        fileIn.close();
        res = 1;
    } catch (IOException i) {
        i.printStackTrace();
    } catch (ClassNotFoundException c) {
        System.out.println("Class not found");
        c.printStackTrace();
    }    
    return list;
}    

}

这是我的FXML控制器中的实现

@FXML
private void createTreatment(ActionEvent event){
   Treatment tr = new Treatment();        
    List<Treatment> list = new ArrayList<Treatment>();
    list = tr.consultListTreatments();

    ObservableList<Material> rows = table.getItems();//FXCollections.observableArrayList();
    //get values of the rows


    Treatament newTreatment = new Treatment(TextFieldTreatmentName.getText(),rows);

    list.add(newTreatment);
    newTreatment.addTreatment(list);  
    TextFieldTreatmentName.clear();
}

我看到了这个问题,但它不符合我的需要,也没有把它修改为我想要的东西。 How to serialize ObservableList

1 个答案:

答案 0 :(得分:0)

在这种情况下,您必须实现Externalizable接口。这将要求您编写自己的方法来序列化和反序列化对象。