You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JavaFX GUI饮食记录数据保存至TXT文件?

问题分析与修复方案

核心问题点

  • 重复绑定按钮事件:你给btnSubmit绑定了两次setOnAction,后绑定的事件会完全覆盖前一次,导致最初的提交逻辑(更新文本域和列表)被丢弃,只执行后一次的逻辑。
  • inputBuffer赋值错误:每次给fP.inputBuffer赋值时都是直接覆盖而非累加,比如连续执行fP.inputBuffer = tfDate.getText() + "\n";和fP.inputBuffer = tfTime.getText() + "\n";后,inputBuffer最终只会保留最后一行(食物量)的数据,写入文件的内容自然不完整。
  • 冗余的文件追加操作:连续两次调用AppentDataToFile()(推测是拼写错误,应为AppendDataToFile()),会把同一份饮食数据重复写入文件。

修复后的代码

// 合并btnSubmit的事件逻辑,避免重复绑定覆盖
btnSubmit.setOnAction((ActionEvent e) -> {
    try {
        // 更新文本域显示内容
        String buf = tA.getText() + "\n";
        buf += tfDate.getText() + "\n";
        buf += tfTime.getText() + "\n";
        buf += tfTypeOfFood.getText() + "\n";
        buf += tfAmtOfFood.getText() + "\n";
        tA.setText(buf);

        // 创建Food对象并添加到列表
        Food newFood = new Food(tfDate.getText(),
                tfTime.getText(),
                tfTypeOfFood.getText(), tfAmtOfFood.getText());
        list.add(newFood);

        // 拼接完整的单条饮食记录,格式和列表展示一致
        String recordContent = newFood.date + "\n"
                + newFood.time + " " + newFood.typeOfFood + " " + newFood.amtOfFood + "\n\n";

        // 写入文件:首次写入用WriteDataToFile,后续追加用AppendDataToFile
        FileProcessing fP = new FileProcessing("FoodDiary.txt");
        fP.inputBuffer = recordContent;
        fP.AppendDataToFile(); // 直接追加到文件末尾,适合多次提交的场景

        // 可选:读取文件内容到buffer,用于验证写入结果
        fP.ReadDataAndStoreToBuffer();

    } catch(Exception ex) {
        tA.setText(ex.toString());
    }
});

// 保留原有的GUI初始化逻辑
VBox vb = new VBox();
vb.setPadding(new Insets(15, 15, 15, 15));
vb.setSpacing(15);
vb.setBackground(new Background(new BackgroundFill(Color.rgb(0, 0, 0), null, null)));
vb.getChildren().addAll(p);

Scene scene = new Scene(vb);
stage.setScene(scene);
stage.setTitle("Food Diary");
stage.setWidth(1100.0);
stage.setHeight(700.0);
stage.show();

关键修改说明

  1. 合并按钮事件:将原本两次分散的btnSubmit事件逻辑合并为一次,确保所有提交相关操作都能执行。
  2. 正确拼接记录内容:先把单条饮食记录的所有字段拼接成完整字符串,再赋值给inputBuffer,保证写入文件的数据完整。
  3. 简化文件操作:只保留一次追加写入逻辑,避免重复写入冗余数据;若需要首次创建文件并写入,可先调用WriteDataToFile,后续提交统一用AppendDataToFile。
  4. 逻辑顺序优化:先完成文本域更新和列表添加,再处理文件写入,代码逻辑更清晰。

内容的提问来源于stack exchange,提问作者Carterjh02

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 22:30:38