Как получить объект пути из 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);
    }
}

Однако я получаю исключение NullPointerException, когда пытаюсь вывести список строк другим методом в классе EditorController следующим образом:

@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


person user3152750    schedule 02.07.2015    source источник


Ответы (1)


Это не имеет ничего общего с тем, как вы получаете файл, проблема в том, что у вас есть два разных экземпляра EditorController. Когда вы выполняете FXMLLoader.load(...), FXMLLoader создает для вас экземпляр вашего класса контроллера и заполняет поля с аннотациями @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();
}

И добавьте атрибут 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);
    }
}
person James_D    schedule 02.07.2015
comment
Что вы подразумеваете под корневым элементом Editor.fxml? - person user3152750; 02.07.2015