我将<Edge>
个对象写入这样的文件
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
new FileOutputStream("Object" + level + ".txt"));
edgeList = koch.getEdgeList();
for (Edge e : edgeList) {
objectOutputStream.writeObject(e);
}
边缘包含颜色:
import java.io.Serializable;
import javafx.scene.paint.Color;
public class Edge implements Serializable {
public double X1, Y1, X2, Y2;
transient public Color color;
public Edge(double X1, double Y1, double X2, double Y2, Color color) {
this.X1 = X1;
this.Y1 = Y1;
this.X2 = X2;
this.Y2 = Y2;
this.color = color;
}
}
我使用javaFX并且无法更改此内容。 我将Color设置为瞬态,因为如果我不这样做会导致Serializable出现问题。
现在我读了这样的对象文件:
FileInputStream streamIn = new FileInputStream("Object" + level + ".txt");
ObjectInputStream objectinputstream = new ObjectInputStream(streamIn);
int teller = 0;
try {
for (teller = 0; teller < i; teller++) {
Edge edge = (Edge) objectinputstream.readObject();
EdgeList.add(edge);
}
} catch (OptionalDataException e) {
if (!e.eof) {
throw e;
}
} finally {
objectinputstream.close();
}
我现在遇到的问题是,当我从文件中读取Edge对象时,坐标(X1,Y1,X2,Y2)读得很好。但颜色为NULL,这不会导致错误,但它不会显示绘制线的颜色。所以我没有任何错误代码。我必须手动设置颜色,但我应该从目标文件中获取颜色。
答案 0 :(得分:0)
为Edge
课程使用自定义序列化表单:
import java.io.Serializable;
import java.io.ObjectInputStream ;
import java.io.ObjectOutputStream ;
import java.io.IOException ;
import javafx.scene.paint.Color;
public class Edge implements Serializable {
public double X1, Y1, X2, Y2;
transient public Color color;
public Edge(double X1, double Y1, double X2, double Y2, Color color) {
this.X1 = X1;
this.Y1 = Y1;
this.X2 = X2;
this.Y2 = Y2;
this.color = color;
}
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeDouble(color.getRed());
s.writeDouble(color.getGreen());
s.writeDouble(color.getBlue());
s.writeDouble(color.getOpacity());
}
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
double red = s.readDouble();
double green = s.readDouble();
double blue = s.readDouble();
double opacity = s.readDouble();
color = Color.color(red, green, blue, opacity);
}
}
这将为您自动序列化颜色数据(rgba值),并在反序列化时从这些数据中重新创建颜色对象。
我创建了一个complete demo,它也使用相同的技术序列化JavaFX属性,但是在这里直接发布有点太长了。