У меня есть java-приложение, создаются и двигаются кролики, задание – сериализация и десериализация объектов. Т.к. ImageView не сериализуемый объект, есть отдельный класс, который делает его сериализуемым
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.io.*;
public class SerializableImageView implements Serializable {
private static final long serialVersionUID = 1L;
private transient ImageView imageView;
private String imagePath;
public SerializableImageView(Image image, String imagePath) {
this.imagePath = imagePath;
this.imageView = new ImageView(image);
}
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(imagePath);
out.writeDouble(imageView.getFitHeight());
out.writeDouble(imageView.getFitWidth());
out.writeDouble(imageView.getTranslateX());
out.writeDouble(imageView.getTranslateY());
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
System.out.println("228");
in.defaultReadObject();
this.imagePath = (String) in.readObject();
this.imageView = new ImageView(new Image(new File(imagePath).toURI().toString()));
this.imageView.setFitHeight((Double) in.readDouble());
this.imageView.setFitWidth((Double) in.readDouble());
this.imageView.setTranslateX((Double) in.readDouble());System.out.println("X:" + imageView.getTranslateX());
this.imageView.setTranslateY((Double) in.readDouble());
}
public ImageView getImageView() {
return imageView;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getImagePath() {
return imagePath;
}
}
также вот классы кроликов
package com.example.laba;
import javafx.scene.Node;
import javafx.scene.image.Image;
import java.io.Serializable;
import java.util.Random;
public abstract class Rabbit implements Serializable {
private static final long serialVersionUID = 5531214745828984045L;
protected String type; // Тип кролика: обычный или альбинос
private Image image;
private static final int SPEED = 5;
protected String normalPath = "rabbit.jpg";
protected String albinoPath = "imgur.jpg";
protected double direction = new Random().nextDouble() * 360;;
protected SerializableImageView serializableImageView;
protected double birthTime;
protected int lifeTime;
protected int id;
protected double x;
protected double y;
public String getNormalPath() {
return normalPath;
}
public void setAlbinoPath(String albinoPath) {
this.albinoPath = albinoPath;
}
public void setNormalPath(String normalPath) {
this.normalPath = normalPath;
}
public String getAlbinoPath() {
return albinoPath;
}
public double getY() {
return y;
}
public double getBirthTime() {
return birthTime;
}
public double getX() {
return x;
}
public Rabbit(SerializableImageView serializableImageView, String type, double birthTime, int lifeTime, int id, double x, double y) {
this.serializableImageView = serializableImageView;
this.type = type;
this.birthTime = birthTime;
this.lifeTime = lifeTime;
this.id = id;
this.x = x;
this.y = y;
}
public SerializableImageView getSerializableImageView() {
return serializableImageView;
}
public void setSerializableImageView(SerializableImageView serializableImageView) {
this.serializableImageView = serializableImageView;
}
public int getLifeTime() {
return lifeTime;
}
public int getId() {
return id;
}
public boolean isExpired(int currentTime) {
return (currentTime - birthTime) >= lifeTime; // Проверяем, истекло ли время жизни кролика
}
public double getElapsedSeconds() {
double currentTime = System.nanoTime() / 1e9; // Текущее время в секундах
return currentTime - birthTime; // Возвращаем разницу между текущим временем и временем рождения
}
public void changeDirection() {
this.direction = new Random().nextDouble() * 360;
}
public String getType() {
return type;
}
public abstract void behave(); // Абстрактный метод для определения поведения
}package com.example.laba;
import javafx.scene.image.Image;
import java.io.*;
public class NormalRabbit extends Rabbit implements Serializable {
private static final Image normalImage = new Image("rabbit.jpg");
private static String imagePath = "rabbit.jpg";
public NormalRabbit(SerializableImageView serializableImageView, double x, double y, double birthTime, int lifetime, int id) {
super(serializableImageView, "normal", birthTime, lifetime, id, x, y);
serializableImageView.getImageView().setImage(normalImage);
serializableImageView.getImageView().setFitWidth(45);
serializableImageView.getImageView().setFitHeight(45);
serializableImageView.getImageView().setTranslateX(x);
serializableImageView.getImageView().setTranslateY(y);
}
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject("rabbit.jpg");
out.writeObject(serializableImageView);
out.writeDouble(this.x);
out.writeDouble(this.y);
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
System.out.println("222");
in.defaultReadObject();
imagePath = (String) in.readObject();
serializableImageView = (SerializableImageView) in.readObject();
this.x = in.readDouble();
this.y = in.readDouble();
}
@Override
public void behave() {
// Реализация поведения обычного кролика
}
}package com.example.laba;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import java.io.*;
import java.util.Objects;
import java.util.Random;
import javafx.scene.image.Image;
public class AlbinoRabbit extends Rabbit implements Serializable {
private static final Image albinoImage = new Image("Imgur.jpg");
private static String imagePath = "imgur.jpg";
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(serializableImageView);
out.writeDouble(this.x);
out.writeDouble(this.y);
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
serializableImageView = (SerializableImageView) in.readObject();
this.x = in.readDouble();
this.y = in.readDouble();
}
public AlbinoRabbit(SerializableImageView serializableImageView, double x, double y, double birthTime, int lifeTime, int id) {
super(serializableImageView, "albino", birthTime, lifeTime, id, x, y);
serializableImageView.getImageView().setImage(albinoImage);
serializableImageView.getImageView().setFitWidth(45);
serializableImageView.getImageView().setFitHeight(45);
serializableImageView.getImageView().setTranslateX(x);
serializableImageView.getImageView().setTranslateY(y);
}
@Override
public void behave() {
// Реализация поведения альбино-кролика
}
}
```, а также место, где происходит сериализация в главном классе
``` @SuppressWarnings("unchecked")
public void loadSimulation(File file) {
pain.setVisible(true);
try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file))) {
System.out.println("Starting loading simulation...");
rabbits.clear();
idSet.clear();
birthTimes.clear();
pain.getChildren().clear();
rabbits = (Vector<Rabbit>) inputStream.readObject();
idSet = (TreeSet<Integer>) inputStream.readObject();
birthTimes = (HashMap<Integer, Double>) inputStream.readObject();
for (Map.Entry<Integer, Double> entry : birthTimes.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", Birth Time: " + entry.getValue());
}
simulationRunning = inputStream.readBoolean();
simulationTimeSeconds = inputStream.readInt();
if (simulationRunning) {
startSimulationLoad();
}
Platform.runLater(() -> {
// Код, который обновляет графический интерфейс JavaFX
pain.setVisible(true);
// Добавляем текстовый элемент для теста
Text testText = new Text("Test Text");
testText.setLayoutX(500);
testText.setLayoutY(500);
pain.getChildren().clear();
pain.getChildren().add(testText);
// Проверяем, что кролики успешно загружены
for (Rabbit rabbit : rabbits) {
SerializableImageView serializableImageView = rabbit.serializableImageView;
pain.getChildren().add(serializableImageView.getImageView());
System.out.println("Loaded rabbit: " + rabbit.serializableImageView.getImagePath() + " " + rabbit.serializableImageView.getImageView().getTranslateX());
}
});
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
}
Вроде все данные, такие как путь к картинке, её расположение и размер считываются правильно, но картинки всё равно не появляются на экране.
Перепробовал всё что угодно, добавлял вывод сообщений после каждой считаной строки, всё корректно, уже не знаю что делать.
Egor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.