在此處輸入影像描述我在 JavaFX 上制作了一個用于創建時間表的 GUI。當我打開應用程式時,我可以將計劃(按鈕)添加到日列(VBox)。ofc 關閉應用程式后不會保存更改:下次打開它時,表是空的。我的問題是如何讓它保存用戶創建的節點,以便下次我打開應用程式時它們在那里?
這是添加節點的確切部分,因為它的價值:
void ask_add_plan(ActionEvent event)
{
Button b = (Button) event.getSource();
VBox v = (VBox) b.getParent();
AnchorPane pop_up = new AnchorPane(); //this pop up is to specify things about the plan
//but i removed unnecessary code for simplicity
VBox pop_up_v = new VBox();
Button add = new Button("Add");
add.setOnAction(e->{
Button plan = new Button(what_to_do.getText());
v.getChildren().add(plan);
container.getChildren().remove(pop_up); //container is the anchor pane everything's in
});
pop_up_v.getChildren().add(add);
pop_up.getChildren().add(pop_up_v);
container.getChildren().add(pop_up); //container is the anchor pane everything's in
}
uj5u.com熱心網友回復:
JavaFX的節點都只是呈現您的資料。他們不是為了得救。將實際資料本身存盤在類中的私有欄位中。
- 在Application.stop方法中,將資料寫入檔案。
- 在您的Application.start方法中,讀取該檔案并使用它來重建 JavaFX 節點。
private static final Path PLANS_FILE =
Path.of(System.getProperty("user.home"), "plans.txt");
private final List<String> plans = new ArrayList<>();
void ask_add_plan(ActionEvent event) {
// ...
add.setOnAction(e -> {
String planText = what_to_do.getText();
plans.add(planText);
Button plan = new Button(planText);
v.getChildren().add(plan);
container.getChildren().remove(pop_up);
});
}
@Override
public void start(Stage primaryStage)
throws Exception {
// ...
if (Files.exists(PLANS_FILE)) {
plans.addAll(Files.readAllLines(PLANS_FILE));
// Add UI elements for each stored plan.
for (String planText : plans) {
Button planButton = new Button(planText);
v.getChildren().add(planButton);
container.getChildren().remove(pop_up);
}
}
}
@Override
public void stop()
throws IOException {
Files.write(PLANS_FILE, plans);
}
以上只是一個簡化的例子。該檔案不必只存盤字串。
我的印象是應用程式中創建的資料比計劃字串更復雜。對于復雜的資料,XML 可能是更合適的檔案格式。或者您可以使用 Java 序列化。或者,您可以發明自己的檔案格式。
您也不必讀取和寫入檔案。如果您熟悉資料庫編程,則可以使用資料庫。或者您可以使用首選項(盡管首選項不太適合存盤復雜資料的串列)。
uj5u.com熱心網友回復:
您應該使用 MVP(模型-視圖-演示者)模式。在 UI 層保存資料不是一個好習慣。使用資料創建模型,然后對其進行序列化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368867.html
下一篇:Unity中的小白框
