我试图像这样获取路径对象:
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
答案 0 :(得分:1)
它与您获取文件的方式无关,问题是您有两个不同的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();
}
并在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);
}
}