【问题标题】:How to automatically load text into Text area如何自动将文本加载到文本区域
【发布时间】:2016-06-22 19:44:00
【问题描述】:

我有一个带有记事本式功能的程序。当我打开它时,我希望从文本文件中保存的文本自动加载到文本区域。

我有两节课。 Writer 类(应该出现保存的文本)和 Load 类,它实际上从文本文件中导入文本。

作家类:

public class Writer extends Application {
private FlowPane notepadLayout = new FlowPane(Orientation.VERTICAL);
private Scene notepadScene = new Scene(notepadLayout,600,300);
private TextArea inputArea = new TextArea();

private void notepadSetup(){
Text titleText = new Text("Notepad");
notepadLayout.getChildren().add(titleText);
notepadLayout.getChildren().add(inputArea);
}

public void start(Stage primaryStage) throws Exception {
notepadSetup();

 Load.loadOperation(); 

primaryStage.setTitle("ROBOT V1!");
primaryStage.setScene(notepadScene);
primaryStage.show();

所以上面的类有文本区域。我想要做的是使用下面的类将文本文件中的信息加载到上面的文本区域中。

public class Load {
private static String line;
static ArrayList<String> x = new ArrayList<>();

 public static void loadOperation(){
    try{
        BufferedReader br = new BufferedReader (new FileReader("Notes.txt"));
        line = br.readLine();

        while(line != null){
             x.add(line);                
            line = br.readLine();
        }
    }catch(Exception e){

    }
    System.out.println(x);
}

Load.loadOperation 行打印出文本文件中的内容。如何让它加载到文本区域?它还必须保存格式(换行符)。

【问题讨论】:

  • 您的代码甚至无法编译。
  • @James_D 现在可以了

标签: java javafx textarea bufferedreader


【解决方案1】:

只需更改方法,使其返回一个字符串。 (我对其进行了更新,使其也使用更现代的 Java。)

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;

public class Load {

    public static String loadOperation() throws IOException {
            return Files.lines(Paths.get("Notes.txt"))
                .collect(Collectors.joining("\n"));

    }
}

那你就做吧

try {
    inputArea.setText(Load.loadOperation());
} catch (IOException exc) {
    exc.printStackTrace();
}

【讨论】:

  • 我可以上传我的 Save 课程,然后您检查它是否是最新的和有效的?
  • 不,只需阅读 API 文档以了解我使用的方法,并查看同一类中的其他类似方法。
【解决方案2】:

从文件中读取文本后,需要将其添加到TextArea 对象中。因此,假设您方便地引用了inputArea,您可以将其附加到(空)控件中:

for (int i = 0; i < x.length; i++) {
    inputArea.appendText(x.get(i));
}

https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextArea.html

【讨论】:

  • 方法是appendText(...),不是append(...)
  • @James_D 在 API 文档中,它列出了两者并说 appendText(...) 已弃用。
  • 您正在链接 AWT 文本区域的 API 文档。您不能在 JavaFX 应用程序中使用 AWT 文本区域。
猜你喜欢
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多