微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

TableView 项目没有刷新,但在从不同的控制器添加后正确添加

如何解决TableView 项目没有刷新,但在从不同的控制器添加后正确添加

首先我想说我已经在这里检查了这个问题的各种类似解决方案,但是发布这个问题的其他用户代码设计与我的非常不同,我不明白如何使用发布的解决方案。

也就是说,我使用 javafx 和 gluon 场景构建器来创建我的第一个应用程序。我将在下面发布代码。这 (https://i.imgur.com/lO2mHZI.png) 是应用程序目前的样子。 “新建”按钮打开此窗口 (https://i.imgur.com/kVZ5tjt.png)。

我有一个名为 WeightApp 的主类:

    package application;
    
    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    
    public class WeightApp extends Application {
    
        @Override
        public void start(Stage primaryStage) throws Exception{
            Parent root = FXMLLoader.load(getClass().getResource("foodTab.fxml"));
            Scene main = new Scene(root);
            primaryStage.setScene(main);
            primaryStage.setTitle("App");
            primaryStage.setMinWidth(root.minWidth(-1));
            primaryStage.setMinHeight(root.minHeight(-1));
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(WeightApp.class);
        }
    }

一个 FoodTabController 类,它加载第一张图片显示内容,而没有按 New 创建的窗口:

    package application;

    import application.domain.Aliment;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.fxml.FXML;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.layout.AnchorPane;
    import javafx.stage.Stage;
    import java.io.*;
    import java.util.Objects;

    public class FoodTabController {

        @FXML
        protected AnchorPane app,foodTab,foodbuttonbar;

        @FXML
        protected TabPane mainWindow;

        @FXML
        protected Tab summaryTabLabel,foodTabLabel;

        @FXML
        protected Label alimentsLabel;

        @FXML
        protected Button deleteButton,refreshButton,newButton,newMealWindow;

        @FXML
        protected TableView<Aliment> alimentsTableView;

        @FXML
        protected TableColumn<Aliment,String> alimentsNameCol;

        @FXML
        protected TableColumn<Aliment,Double> alimentsKcalCol,alimentsFatCol,alimentsCarbsCol,alimentsProteinCol,alimentsFiberCol;

        protected ObservableList<Aliment> aliments = FXCollections.observableArrayList();

        public void initialize() {
            alimentsNameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
            alimentsKcalCol.setCellValueFactory(new PropertyValueFactory<>("calories"));
            alimentsFatCol.setCellValueFactory(new PropertyValueFactory<>("fat"));
            alimentsCarbsCol.setCellValueFactory(new PropertyValueFactory<>("carbohydrate"));
            alimentsProteinCol.setCellValueFactory(new PropertyValueFactory<>("protein"));
            alimentsFiberCol.setCellValueFactory(new PropertyValueFactory<>("fiber"));

            loadaliments();

            alimentsTableView.setItems(aliments);

        }

        // Aliments //

        public void newAlimentwindow() throws IOException {
            Parent newAlimentwindow = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("newAlimentwindow.fxml")));
            Stage stage = new Stage();
            stage.setScene(new Scene(newAlimentwindow));
            stage.show();
        }

        public void updateTableView() {
            aliments.clear();
            loadaliments();
        }

        public ObservableList<Aliment> alimentObservableList() {
            return aliments;
        }

        public void deletealiment() {
            aliments.remove(alimentsTableView.getSelectionModel().getSelectedItem());
            saveAliments();
        }

        public void saveAliments() {
            String COMMA_DELIMITER = ",";
            String NEW_LINE_SEParaTOR = "\n";
            String FILE_HEADER = "aliment,calories,fat,carbs,protein,fiber";

            FileWriter fw = null;

            try {
                fw = new FileWriter("aliments.csv");

                fw.append(FILE_HEADER);
                fw.append(NEW_LINE_SEParaTOR);

                for (Aliment aliment : aliments) {
                    fw.append(String.valueOf(aliment.getName()));
                    fw.append(COMMA_DELIMITER);
                    fw.append(String.valueOf(aliment.getCalories()));
                    fw.append(COMMA_DELIMITER);
                    fw.append(String.valueOf(aliment.getFat()));
                    fw.append(COMMA_DELIMITER);
                    fw.append(String.valueOf(aliment.getCarbohydrate()));
                    fw.append(COMMA_DELIMITER);
                    fw.append(String.valueOf(aliment.getProtein()));
                    fw.append(COMMA_DELIMITER);
                    fw.append(String.valueOf(aliment.getFiber()));
                    fw.append(NEW_LINE_SEParaTOR);
                }
            } catch (Exception e) {
                System.out.println("Error writing to file");
                e.printstacktrace();
            } finally {
                try {
                    assert fw != null;
                    fw.flush();
                    fw.close();
                } catch (IOException e) {
                    System.out.println("Error while flushing/closing FileWriter.");
                    e.printstacktrace();
                }
            }
        }

        public void loadaliments()  {
            String COMMA_DELIMITER = ",";
            int ALIMENT_NAME = 0;
            int ALIMENT_CALORIES = 1;
            int ALIMENT_FAT = 2;
            int ALIMENT_CARBS = 3;
            int ALIMENT_PROTEIN = 4;
            int ALIMENT_FIBER = 5;

            BufferedReader fileReader = null;

            try {
                fileReader = new BufferedReader(new FileReader("aliments.csv"));
                fileReader.readLine();
                String line = "";

                while ((line = fileReader.readLine()) != null) {
                    String[] tokens = line.split(COMMA_DELIMITER);
                    aliments.add(new Aliment(String.valueOf(tokens[ALIMENT_NAME]),Double.parseDouble(tokens[ALIMENT_CALORIES]),Double.parseDouble(tokens[ALIMENT_FAT]),Double.parseDouble(tokens[ALIMENT_CARBS]),Double.parseDouble(tokens[ALIMENT_PROTEIN]),Double.parseDouble(tokens[ALIMENT_FIBER])));

                }
            } catch (Exception e) {
                System.out.println("Error reading aliments from CSV file");
                e.printstacktrace();
            } finally {
                try {
                    assert fileReader != null;
                    fileReader.close();
                } catch (IOException e) {
                    System.out.println("Error while trying to close FileReader");
                    e.printstacktrace();
                }
            }

        }
        // Aliments //
    }

最后,我有 newAlimentwindowController 类,它是 New 按钮打开的窗口:

    package application;

    import application.domain.Aliment;
    import javafx.fxml.FXML;
    import javafx.scene.control.Button;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.Pane;

    public class newAlimentwindowController extends FoodTabController {

        @FXML
        protected Pane newAlimentPane;

        @FXML
        protected TextField newAlimentSetName,newAlimentSetCal,newAlimentSetFat,newAlimentSetCarbs,newAlimentSetProtein,newAlimentSetFiber;

        @FXML
        protected Button addButton;

        public void initialize() {
            loadaliments();
        }

        public void addaliment() {
            aliments.add(new Aliment(newAlimentSetName.getText(),Double.parseDouble(newAlimentSetCal.getText()),Double.parseDouble(newAlimentSetFat.getText()),Double.parseDouble(newAlimentSetCarbs.getText()),Double.parseDouble(newAlimentSetProtein.getText()),Double.parseDouble(newAlimentSetFiber.getText())));
            saveAliments();
            updateTableView();
        }
    }

此外,Aliment 对象:

    package application.domain;
    
    import java.util.Objects;
    
    public class Aliment {
    
        private String name;
        private double weight;
        private double calories,carbohydrate,fiber;
    
        public Aliment(String name,double weight,double calories,double fat,double carbohydrate,double protein,double fiber) {
           this(name,fiber);
           this.weight = weight;
        }
    
        public Aliment(String name,double fiber) {
            this.name = name;
            this.weight = 100;
            this.calories = calories;
            this.fat = fat;
            this.carbohydrate = carbohydrate;
            this.protein = protein;
            this.fiber = fiber;
        }

一切正常,除了在新窗口中输入文本字段并按下添加按钮后,addaliment 方法中的 updateTableView 方法不会触发(正确添加了 Aliment 项目,可观察列表只是没有) t 刷新添加按钮按下)。但是,如果我从链接到“刷新”按钮的 FoodTabController 类内部触发它,则 updateTableView 方法确实有效。

我不明白发生了什么:我可以从 newAlimentwindowController 与 FoodTabController 中的 aliments observable 列表交互,因为 aliments.add 有效,同时,saveAliments 方法也有效,但 updateTableView 方法,在同一个方法中作为 saveAliments 和 aliments.add,不起作用。我很困惑。

我觉得我缺少一些关于 Java 编程的基本知识,因此我想了解发生了什么。任何帮助将不胜感激,非常感谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。