我正在尝试获取这样的路径对象:

private Path file;
private String fileContent;
private Parent root;

@FXML
public void handleOpenFileAction(ActionEvent event) {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Open a File");
    this.file = Paths.get(fileChooser.showOpenDialog(new Stage()).toURI());

    try {
        List<String> lines = Files.readAllLines(this.file, Charset.defaultCharset());

        EditorController editorController = new EditorController();
        editorController.openEditor(lines);

    } catch(IOException ex) {
        System.out.println(ex);
    }
}


但是,当我尝试在EditorController类的另一个方法中输出字符串列表时,出现NullPointerException异常,如下所示:

@FXML
public TextArea textareaContent;

public Parent root;

public void openEditor(List<String> lines) throws IOException {
    this.root = FXMLLoader.load(getClass().getResource("/com/HassanAlthaf/Editor.fxml"));

    Scene scene = new Scene(this.root);

    Stage stage = new Stage();

    stage.setScene(scene);
    stage.setTitle("Editting File");
    for(String line : lines) {
        this.textareaContent.appendText(line + "\n");
    }
    stage.show();
}


这正是我得到的:http://pastebin.com/QtzQ9RVZ

EditorController.java:40是以下代码:this.textareaContent.appendText(line + "\n");

TextEditorController.java:38是以下代码:editorController.openEditor(lines);

如何正确获取它,然后在TextArea上显示它?请注意,我要使用java.nio而不是java.io

最佳答案

它与获取文件的方式无关,问题是您有两个不同的EditorController实例。当执行FXMLLoader.load(...)时,FXMLLoader为您创建控制器类的实例,并填充带@FXML的字段。因此该实例已初始化textAreaContent,但是您使用new EditorController()创建的实例(以及您正在调用openEditor的实例)没有初始化。

像这样重构它:

EditorController:

@FXML
public TextArea textareaContent;

@FXML
private Parent root;

public void openEditor(List<String> lines) throws IOException {
    Scene scene = new Scene(this.root);

    Stage stage = new Stage();

    stage.setScene(scene);
    stage.setTitle("Editting File");
    for(String line : lines) {
        this.textareaContent.appendText(line + "\n");
    }
    stage.show();
}


并将fx:id="root"属性添加到Editor.fxml的根元素。

然后做

@FXML
public void handleOpenFileAction(ActionEvent event) {
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Open a File");
    this.file = Paths.get(fileChooser.showOpenDialog(new Stage()).toURI());
    // note the slightly cleaner version:
    // this.file = fileChooser.showOpenDialog(new Stage()).toPath();


    try {
        List<String> lines = Files.readAllLines(this.file, Charset.defaultCharset());

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/HassanAlthaf/Editor.fxml"));
        Parent root = loader.load();
        EditorController editorController = loader.getController();
        editorController.openEditor(lines);

    } catch(IOException ex) {
        System.out.println(ex);
    }
}

09-04 13:25