Java 构建一个面板,在其中选择保存文件的位置

Java 构建一个面板,在其中选择保存文件的位置,java,swing,jfilechooser,Java,Swing,Jfilechooser,我会建立一个面板,让我选择我可以保存文件的地方。我阅读了java文档,发现有一个名为file chooser的swing组件,但我不知道如何使用它。我想做的是选择在我的计算机中保存创建文件的路径。这是直接从Oracle网站上获取的,是学习FileChooser的好地方 final JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser

我会建立一个面板,让我选择我可以保存文件的地方。我阅读了java文档,发现有一个名为file chooser的swing组件,但我不知道如何使用它。我想做的是选择在我的计算机中保存创建文件的路径。

这是直接从Oracle网站上获取的,是学习FileChooser的好地方

final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);

if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    //This is where a real application would open the file.
    log.append("Opening: " + file.getName() + ".");
} else {
    log.append("Open command cancelled by user.");
}

上述代码打开一个文件选择器,并将所选文件存储在
fc
变量中。所选按钮(确定、取消等)存储在
returnVal
中。然后,您可以对该文件执行任何操作。

如何使用它?嗯,你只需要“使用它”!真的

这将创建FileChooser实例,并将其设置为从用户的桌面文件夹开始:

JFileChooser fc = new JFileChooser(System.getProperty("user.home") + "/Desktop");
之后,您可以设置各种选项。在本例中,我将其设置为允许选择多个文件,并且只允许选择“.xls”(Excel)文件:

最后,我将展示它并获得用户的选择和选择的文件:

File[] chosenFiles;
int choice = fc.showOpenDialog(fc);
        if (choice == JFileChooser.APPROVE_OPTION) {
            chosenFiles = fc.getSelectedFiles();
        } else {
        //User canceled. Do whatever is appropriate in this case.
        }

享受吧!祝你好运

你太好了,adchilds。使用JFileChooser()有一百万个链接。一个附录:如果您想要“仅目录”,请添加
fc.setFileSelectionMode(JFileChooser.directories)
File[] chosenFiles;
int choice = fc.showOpenDialog(fc);
        if (choice == JFileChooser.APPROVE_OPTION) {
            chosenFiles = fc.getSelectedFiles();
        } else {
        //User canceled. Do whatever is appropriate in this case.
        }