У меня есть программа Java FX, где у меня есть класс модели данных, который содержит все данные модели.В графическом интерфейсе есть разные фигуры (соответствующие данным в классе модели данных).Я пытаюсь найти способ сохранить все данные модели и фигуры в графическом интерфейсе до закрытия приложения пользователем, поэтому, когда приложение запускается снова, я могу загрузить сохраненные данные.
Я пыталсяиспользуя Serializable и сохраните данные в файл, а затем загрузите данные из файла, но я думаю, что, возможно, я что-то делаю не так, поскольку он не работает.
Мой класс DataModel, который содержит наблюдаемые данные (в основном, получатели иsetters):
public class DataModel implements java.io.Serializable {
private static final long serialVersionUID = 1L;
@SuppressWarnings("rawtypes")
private ObservableList<UndirectedNonWeightedGraph> undirectedNonWeightedGraphData = FXCollections.observableArrayList();
@SuppressWarnings("rawtypes")
private ObservableList<UndirectedWeightedGraph> undirectedWeightedGraphData = FXCollections.observableArrayList();
@SuppressWarnings("rawtypes")
private ObservableList<DirectedNonWeightedGraph> directedNonWeightedGraphData = FXCollections.observableArrayList();
@SuppressWarnings("rawtypes")
private ObservableList<DirectedWeightedGraph> directedWeightedGraphData = FXCollections.observableArrayList();
private ObservableList<Vertex<Integer>> vertexDataUndirectedNonWeightedInt = FXCollections.observableArrayList();
private ObservableList<Vertex<Double>> vertexDataUndirectedNonWeightedDouble = FXCollections.observableArrayList();
private ObservableList<Vertex<String>> vertexDataUndirectedNonWeightedString = FXCollections.observableArrayList();
private ObservableList<Vertex<Integer>> vertexDataUndirectedWeightedInt = FXCollections.observableArrayList();
private ObservableList<Vertex<Double>> vertexDataUndirectedWeightedDouble = FXCollections.observableArrayList();
private ObservableList<Vertex<String>> vertexDataUndirectedWeightedString = FXCollections.observableArrayList();
private ObservableList<Vertex<Integer>> vertexDataDirectedNonWeightedInt = FXCollections.observableArrayList();
private ObservableList<Vertex<Double>> vertexDataDirectedNonWeightedDouble = FXCollections.observableArrayList();
private ObservableList<Vertex<String>> vertexDataDirectedNonWeightedString = FXCollections.observableArrayList();
private ObservableList<Vertex<Integer>> vertexDataDirectedWeightedInt = FXCollections.observableArrayList();
private ObservableList<Vertex<Double>> vertexDataDirectedWeightedDouble = FXCollections.observableArrayList();
private ObservableList<Vertex<String>> vertexDataDirectedWeightedString = FXCollections.observableArrayList();
private UndirectedNonWeightedGraph<Integer> undirectedNonWeightedInt;
private UndirectedNonWeightedGraph<Double> undirectedNonWeightedDouble;
private UndirectedNonWeightedGraph<String> undirectedNonWeightedString;
private UndirectedWeightedGraph<Integer> undirectedWeightedInt;
private UndirectedWeightedGraph<Double> undirectedWeightedDouble;
private UndirectedWeightedGraph<String> undirectedWeightedString;
private DirectedNonWeightedGraph<Integer> directedNonWeightedInt;
private DirectedNonWeightedGraph<Double> directedNonWeightedDouble;
private DirectedNonWeightedGraph<String> directedNonWeightedString;
private DirectedWeightedGraph<Integer> directedWeightedInt;
private DirectedWeightedGraph<Double> directedWeightedDouble;
private DirectedWeightedGraph<String> directedWeightedString;
private ArrayList<Vertex<Integer>> listOfUndirectedNonWeightedIntVertices;
private ArrayList<Vertex<Double>> listOfUndirectedNonWeightedDoubleVertices;
private ArrayList<Vertex<String>> listOfUndirectedNonWeightedStringVertices;
private ArrayList<Vertex<Integer>> listOfUndirectedWeightedIntVertices;
private ArrayList<Vertex<Double>> listOfUndirectedWeightedDoubleVertices;
private ArrayList<Vertex<String>> listOfUndirectedWeightedStringVertices;
private ArrayList<Vertex<Integer>> listOfDirectedNonWeightedIntVertices;
private ArrayList<Vertex<Double>> listOfDirectedNonWeightedDoubleVertices;
private ArrayList<Vertex<String>> listOfDirectedNonWeightedStringVertices;
private ArrayList<Vertex<Integer>> listOfDirectedWeightedIntVertices;
private ArrayList<Vertex<Double>> listOfDirectedWeightedDoubleVertices;
private ArrayList<Vertex<String>> listOfDirectedWeightedStringVertices;
public DataModel() {
this.undirectedNonWeightedInt = new UndirectedNonWeightedGraph<Integer>();
this.undirectedNonWeightedDouble = new UndirectedNonWeightedGraph<Double>();
this.undirectedNonWeightedString = new UndirectedNonWeightedGraph<String>();
this.undirectedWeightedInt = new UndirectedWeightedGraph<Integer>();
this.undirectedWeightedDouble = new UndirectedWeightedGraph<Double>();
this.undirectedWeightedString = new UndirectedWeightedGraph<String>();
this.directedNonWeightedInt = new DirectedNonWeightedGraph<Integer>();
this.directedNonWeightedDouble = new DirectedNonWeightedGraph<Double>();
this.directedNonWeightedString = new DirectedNonWeightedGraph<String>();
this.directedWeightedInt = new DirectedWeightedGraph<Integer>();
this.directedWeightedDouble = new DirectedWeightedGraph<Double>();
this.directedWeightedString = new DirectedWeightedGraph<String>();
undirectedNonWeightedGraphData.addAll(undirectedNonWeightedInt, undirectedNonWeightedDouble, undirectedNonWeightedString);
undirectedWeightedGraphData.addAll(undirectedWeightedInt,undirectedWeightedDouble,undirectedWeightedString);
directedNonWeightedGraphData.addAll(directedNonWeightedInt,directedNonWeightedDouble,directedNonWeightedString);
directedWeightedGraphData.addAll(directedWeightedInt,directedWeightedDouble,directedWeightedString);
listOfUndirectedNonWeightedIntVertices = new ArrayList<Vertex<Integer>>();
listOfUndirectedNonWeightedDoubleVertices = new ArrayList<Vertex<Double>>();
listOfUndirectedNonWeightedStringVertices = new ArrayList<Vertex<String>>();
listOfUndirectedWeightedIntVertices = new ArrayList<Vertex<Integer>>();
listOfUndirectedWeightedDoubleVertices = new ArrayList<Vertex<Double>>();
listOfUndirectedWeightedStringVertices = new ArrayList<Vertex<String>>();
listOfDirectedNonWeightedIntVertices = new ArrayList<Vertex<Integer>>();
listOfDirectedNonWeightedDoubleVertices = new ArrayList<Vertex<Double>>();
listOfDirectedNonWeightedStringVertices = new ArrayList<Vertex<String>>();
listOfDirectedWeightedIntVertices = new ArrayList<Vertex<Integer>>();
listOfDirectedWeightedDoubleVertices = new ArrayList<Vertex<Double>>();
listOfDirectedWeightedStringVertices = new ArrayList<Vertex<String>>();
}
//REST OF CLASS IS JUST GETTERS AND SETTERS SO WONT INCLUDE
}
Я создал класс ResourceManager с методами сохранения и загрузки:
public class ResourceManager {
public static void save(Serializable data, String fileName) throws Exception {
try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(Paths.get(fileName)))) {
oos.writeObject(data);
}
}
public static Object load(String fileName) throws Exception {
try (ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(Paths.get(fileName)))) {
return ois.readObject();
}
}
}
В своем основном методе я пытаюсь вызвать методы сохранения и загрузки соответствующим образом и пытаюсьсохранить в файл:
public class Main extends Application {
private Stage primaryStage;
private DataModel dataModel;
private GraphPanelController controller;
public Main() {
dataModel = new DataModel();
}
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("Graph Visualiser");
showGraphPanel();
primaryStage.setOnCloseRequest(e->{
saveData();
});
}
public void showGraphPanel() {
try {
// Load person overview.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/GraphPanel.fxml"));
AnchorPane graphPanel = (AnchorPane) loader.load();
// Give the controller access to the main app.
controller = loader.getController();
controller.setMain(this);
controller.setDataModel(dataModel);
loadData();
//Show the scene containing the root layout.
Scene scene = new Scene(graphPanel);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean showAddVertexPopUp(GraphPanelController gpc) {
try {
// Load the fxml file and create a new stage for the popup dialog.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/AddVertexData.fxml"));
AnchorPane page = (AnchorPane) loader.load();
// Create the dialog Stage.
Stage dialogStage = new Stage();
dialogStage.setTitle("Add vertex data");
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.initOwner(primaryStage);
Scene scene = new Scene(page);
dialogStage.setScene(scene);
// Set the person into the controller.
AddVertexDataController controller = loader.getController();
controller.setDialogStage(dialogStage);
controller.setGraphPanelController(gpc);
controller.setMain(this);
controller.setDataModel(dataModel);
// Show the dialog and wait until the user closes it
dialogStage.showAndWait();
return controller.isOkClicked();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void saveData() {
try {
ResourceManager.save(dataModel, "1.save");
}catch(Exception e) {
}
}
public void loadData() {
try {
dataModel = (DataModel) ResourceManager.load("1.save");
}
catch (Exception e) {
System.out.println("Couldn't load save data: " + e.getMessage());
}
}
/**
* Returns the main stage.
* @return
*/
public Stage getPrimaryStage() {
return primaryStage;
}
public static void main(String[] args) {
launch(args);
}
Любая помощь будет с благодарностью!
Спасибо.