如何从 FileChooser JavaFX 获取路径对象

How to fetch a Path Object from FileChooser JavaFX

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

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 class 中的另一个方法中输出字符串列表时,我得到一个 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");

文本EditorController.java:38是这个代码:editorController.openEditor(lines);

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

这与您获取文件的方式无关,问题是您有两个不同的 EditorController 实例。当您执行 FXMLLoader.load(...) 时,FXMLLoader 会为您创建控制器实例 class 并填充 @FXML 注释字段。所以那个实例已经textAreaContent初始化了,但是你用new EditorController()创建的实例(你正在调用openEditor)没有。

重构如下:

编辑控制器:

@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();
}

并向 Editor.fxml 的根元素添加一个 fx:id="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());
    // 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);
    }
}