将文本文件加载到 JavaFX 中的 TextArea

Load text file into TextArea in JavaFX

我需要在 javaFX 中将文本文件显示到 TextArea 中。 我厌倦了使用这段代码:

@FXML
private void viewHistory(ActionEvent event) throws FileNotFoundException, IOException {
    HistoryController hc = new HistoryController();
    BufferedReader in;
    try {
        in = new BufferedReader(new FileReader("EmployeeUpdateHistory.txt"));
        String str;
        File f = new File("EmployeeUpdateHistory.txt");
        Scanner input = new Scanner(f);

        while ((str = in.readLine())!=null) {
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().getResource("/view/history.fxml"));
            loader.load();
            Parent root = loader.getRoot();
            Stage s1 = new Stage();
            HistoryController historyController = loader.getController();
            historyController.tfHistory.appendText(str);
            Scene s2 = new Scene(root);
            s1.setScene(s2);
            s1.setTitle("History");
            s1.setResizable(false);
            s1.show();
    }

    } catch (FileNotFoundException ex) {
        System.err.println(ex);
    }

}

但它只在 TextArea 中显示一行并打开多个阶段(等于行号)。

您用于创建和显示舞台的代码在 while 循环内。因此它将对文件中的每一行执行。尝试将该代码移到循环之外,只需要在循环内附加文本即可。

像这样:

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/view/history.fxml"));
loader.load();
Parent root = loader.getRoot();
Stage s1 = new Stage();
Scene s2 = new Scene(root);
s1.setScene(s2);
s1.setTitle("History");
s1.setResizable(false);

HistoryController historyController = loader.getController();
while ((str = in.readLine())!=null) {
    historyController.tfHistory.appendText(str);       
}

s1.show();