如何使JavaFX TreeView和TreeItem可序列化



我在尝试使用ObjectOutputStream保存TreeView时遇到此错误(java.io.NotSerializableException:javafx.scene.control.TreeView(。

我有两个类实现了Serializable,还有一个主类不实现Serializable。

这两个类别是供应商和地址。Vendor类包含4个变量(名称、年龄、性别、address类类型的地址(,构造函数使用set方法设置所有变量,构造函数仅使用set方法来设置名称变量,以及变量的get/set方法。

地址类包含2个变量(街道名称和邮政编码(,默认构造函数使用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);
}
}

无法序列化节点(可能除了您自己实现的自定义节点(,因为内部状态太多,无法恢复。由于无法向节点添加方法/接口(而不扩展它们(,因此无法添加Serializable接口并添加方法来保存恢复状态和正确读取数据所需的数据部分。

你最好创建一个可序列化的包装类,让你可以恢复你真正感兴趣的属性;加载数据时创建一个新节点,并用加载的数据填充。

以下示例显示了如何使用TreeItem<? extends Serializable>执行此操作;缺少数据,例如扩展的属性,但您应该能够恢复value属性和子级。(实现比具有小深度的TreeItem结构所需的要复杂一些,但在某些深度,您需要注意,更简单的递归方法可能会导致StackOverflowErrors。(

在这种情况下,每个项都是通过写入子项的数量(它自己的值属性(来序列化的,然后对每个子项执行同样的操作。这会产生一系列可用于恢复数据的int和value对:

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;
}
}

有关readObjectreadResolvewriteObject如何工作的描述,请参阅Serializable的javadoc

相关内容

  • 没有找到相关文章

最新更新