如何从JFileChooser中获取选定文件的属性

问题描述:

我有一个带有文本字段的FXML控制器类,我希望通过FileChooser来选择文件的各种文件属性。如何从JFileChooser中获取选定文件的属性

控制器看起来像:

@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"

+0

为什么不使用JavaFX的[文件选择](http://docs.oracle.com/javafx/2/api/javafx/stage/FileChooser.html),而不是摆动的JFileChooser? – 2014-08-29 09:55:01

+0

Hi @JoopEggen Eggen。我结束了。唯一的区别是我将使用[FileChooser](http://docs.oracle.com/javafx/2/api/javafx/stage/FileChooser.html),但仍然是同样的问题。我真的不介意我将使用什么,FileChooser或swing JFileChooser,我只想从控制器获取'documentName.setText(file.getName());'从另一个类中检索FileChooser。 – 2014-08-29 10:19:08

唯一的NullPointerException可能为documentName仍然为空。也就是说,@FXML不起作用。检查异常的行号以查看是否是这种情况。然后查看您加载的.fxml文件。

@FXML(name="documentName") 
public TextField documentName;