Java 如何从JFileChooser获取选定文件的属性
我有一个带有文本字段的FXML控制器类,我想用用户通过文件选择器选择的文件的各种文件属性填充该字段 控制器看起来像:Java 如何从JFileChooser获取选定文件的属性,java,textfield,jfilechooser,Java,Textfield,Jfilechooser,我有一个带有文本字段的FXML控制器类,我想用用户通过文件选择器选择的文件的各种文件属性填充该字段 控制器看起来像: @FXML TextField documentName; File file; public void attachNewDocFileChooser() { file = new MyFileChooser().chooser(); if (file != null) { documentName.setText(file.getName(
@FXML
TextField documentName;
File file;
public void attachNewDocFileChooser() {
file = new MyFileChooser().chooser();
if (file != null) {
documentName.setText(file.getName());
} else {
documentName.setText("No file selected");
}
}
文件选择器是在不同的类中创建的MyFileChooser
:
@FXML
public File chooser() {
File file = null;
final JFileChooser fileDialog = new JFileChooser();
int returnVal = fileDialog.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileDialog.getSelectedFile();
}
return file;
}
我无法用所选文件的名称填充文本字段documentName
我将非常感谢您对我的帮助。提前谢谢大家
更新:
我得到一个java.lang.NullPointerException
我还忘了提到
chooser()
链接到一个标签,因此onMouseClicked=“#chooser”
唯一的NullPointerException可能是documentName
仍然为空。也就是说,@FXML
不起作用。检查异常的行号以查看是否是这种情况。然后查看加载的.fxml文件
@FXML(name="documentName")
public TextField documentName;
为什么不使用JavaFX而不是swing JFileChooser呢。我的结局也一样。唯一的区别是,我将使用,但仍然是相同的问题。我并不介意我将使用什么,FileChooser或swing JFileChooser,我只想
documentName.setText(file.getName())代码>从控制器中,从另一个类检索FileChooser。