我如何使JavaFX TreeView和TreeItem可序列化?

问题描述 投票:2回答:1

尝试使用ObjectOutputStream保存我的TreeView时出现此错误(java.io.NotSerializableException:javafx.scene.control.TreeView)。

我有2个实现Serializable的类和1个不实现Serializable的主类。

2类是供应商和地址。供应商类包含4个变量(名称,年龄,性别,地址类类型的地址),使用set方法设置所有变量的构造函数,使用set方法仅设置名称变量的构造函数以及用于变量。

地址类包含2个变量(街道名称和邮政编码),使用set方法设置变量的默认构造函数以及变量的get / set方法。

这是我的主班

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SimpleTreeView extends Application {

  private TreeView<Vendor> treeView;

  public void start(Stage stage) {
    stage.setTitle("Simple TreeView");

    treeView = new TreeView<>();
    TreeItem<Vendor> root = new TreeItem<>(new Vendor("Root"));
    root.setExpanded(true);
    treeView.setRoot(root);
    treeView.setShowRoot(false);
    TreeItem<Vendor> start = new TreeItem<>(new Vendor("Start"));
    root.getChildren().add(start);

    Button saveButton = new Button("Save");
    saveButton.setOnMouseClicked(event -> saveTreeView(stage));

    VBox vBox = new VBox(20);
    vBox.getChildren().addAll(treeView, saveButton);

    stage.setScene(new Scene(vBox));

    stage.show();
  }

  private void saveTreeView(Stage stage) {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Save");
    File file = fileChooser.showSaveDialog(stage);

    if (file != null) {
      try {
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file));
        os.writeObject(treeView);
        os.close();
      }
      catch (Exception e) {
        System.out.println(e);
      }
    }
  }

  public static void main(String[] args) {
    launch(args);
  }

}
java javafx treeview notserializableexception
1个回答
0
投票

节点无法序列化(可能是您自己实现的自定义节点除外),内部状态太多,很难恢复。缺少向节点添加方法/接口(不扩展它们)的可能性,因此无法添加Serializable接口和添加方法来保存恢复状态并正确读取此数据所需的那些数据部分。 >

最好创建一个可序列化的包装器类,该类可让您还原实际感兴趣的属性。恕我直言,最好不要尝试序列化节点;加载数据时创建一个新节点,并用加载的数据填充它。

以下示例显示了如何使用TreeItem<? extends Serializable>可以做到这一点;缺少诸如扩展属性之类的数据,但是您应该能够恢复value属性和子级。 (该实现比深度较小的TreeItem结构所需的要复杂一些,但是某些深度您需要注意,更简单的递归方法可能会导致StackOverflowError。)

在这种情况下,每个项目都通过写入子代的数量进行序列化,它是自己的value属性,然后对每个子代执行相同的操作。这导致可以用于还原数据的int和值对的序列:

public class TreeItemSerialisation {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        TreeItem<String> root = new TreeItem<>("root");
        TreeItem<String> c1 = new TreeItem<>("root.1");
        TreeItem<String> c3 = new TreeItem<>("root.3");
        root.getChildren().addAll(c1, new TreeItem<>("root.2"), c3);
        TreeItem<String> c3_1 = new TreeItem<>("root.3.1");
        c3_1.getChildren().add(new TreeItem<>("root.3.1.1"));
        c3.getChildren().add(c3_1);
        c1.getChildren().addAll(new TreeItem<>("root.1.1"), new TreeItem<>("root.1.2"));

        // serialize
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(new TreeItemSerialisationWrapper(root));
        }

        // unserialize
        TreeItem<String> root2;
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()))) {
            root2 = (TreeItem<String>) ois.readObject();
        }
        // TODO do something with root2
    }

}
public class TreeItemSerialisationWrapper<T extends Serializable> implements Serializable {
    private static final long serialVersionUID = 1L;

    private transient TreeItem<T> item;

    public TreeItemSerialisationWrapper(TreeItem<T> item) {
        if (item == null) {
            throw new IllegalArgumentException();
        }
        this.item = item;
    }

    /**
     * Custom way of writing the TreeItem structure
     */
    private void writeObject(ObjectOutputStream out)
             throws IOException {
        Stack<TreeItem<T>> stack = new Stack<>();
        stack.push(item);

        out.defaultWriteObject();
        do {
            TreeItem<T> current = stack.pop();

            int size = current.getChildren().size();
            out.writeInt(size);

            // write all the data that needs to be restored here
            out.writeObject(current.getValue());

            // "schedule" serialisation of children.
            // the first one is inserted last, since the top one from the stack is
            // retrieved first
            for (int i = size - 1; i >= 0; --i) {
                stack.push(current.getChildren().get(i));
            }
        } while (!stack.isEmpty());
    }

    /**
     * happens before readResolve; recreates the TreeItem structure
     */
    private void readObject(ObjectInputStream in)
             throws IOException, ClassNotFoundException {
        class Container {
            int count;
            final TreeItem<T> item;
            Container(ObjectInputStream in) throws ClassNotFoundException, IOException {
                // read the data for a single TreeItem here
                this.count = in.readInt();
                this.item = new TreeItem<>((T) in.readObject());
            }
        }
        in.defaultReadObject();
        Container root = new Container(in);
        this.item = root.item;

        if (root.count > 0) {
            Stack<Container> stack = new Stack<>();
            stack.push(root);
            do {
                Container current = stack.peek();
                --current.count;
                if (current.count <= 0) {
                    // we're done with this item
                    stack.pop();
                }

                Container newContainer = new Container(in);
                current.item.getChildren().add(newContainer.item);
                if (newContainer.count > 0) {
                    //schedule reading children of non-leaf
                    stack.push(newContainer);
                }
            } while(!stack.isEmpty());
        }
    }

    /** 
     * We're not actually interested in this object but the treeitem
     * @return the treeitem
     * @throws ObjectStreamException
     */
    private Object readResolve() throws ObjectStreamException {
        return item;
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.