JFileChooser - 自定义文件名(创建新文件)

4

在使用JFileChooser保存文件时,我可能忽略了一些明显的API问题。我只能选择预先存在的文件进行保存,而不能输入新名称并将其保存。这是否可能使用JFileChooser实现,或者我应该使用其他API?

以下是我尝试实现此功能的代码:

public static File getUserFile() {      
    final SaveFileChooser fc = new SaveFileChooser();

    fc.setAcceptAllFileFilterUsed(false);

    for(FileFilter ch : FileFilterUtils.getAllFilters()) {
        fc.addChoosableFileFilter(ch);
    }       

    int option = fc.showSaveDialog(JPad.getFrame());

    if (option == JFileChooser.APPROVE_OPTION) {
        return fc.getSelectedFile();
    } 
    return null;
}

public static class SaveFileChooser extends JFileChooser {
    private static final long serialVersionUID = -8175471295012368922L;

    @Override
    public void approveSelection() {
        File f = getSelectedFile();
        if(f.exists() && getDialogType() == SAVE_DIALOG){
            int result = JOptionPane.showConfirmDialog(JPad.getFrame(), "The file exists, overwrite?", "Existing file", JOptionPane.YES_NO_CANCEL_OPTION);

            switch(result){
            case JOptionPane.YES_OPTION:
                super.approveSelection();
                return;
            case JOptionPane.NO_OPTION:
                return;
            case JOptionPane.CLOSED_OPTION:
                return;
            case JOptionPane.CANCEL_OPTION:
                cancelSelection();
                return;
            }
        }
    }
}

请查看此帖子和此帖子。 - user1874520
这是Oracle提供的一个示例:http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/FileChooserDemoProject/src/components/FileChooserDemo.java - Aksel Willgert
2个回答

4
检查你的if条件:
if(f.exists() && getDialogType() == SAVE_DIALOG)

如果f不存在(这是您希望能够实现的情况),会发生什么?

您可以尝试以下操作:

if(getDialogType() == SAVE_DIALOG) {
    if(f.exists()) {
        // your overwrite checking
    } else {
        super.approveSelection();
        return;
    }
}

1

试一下这个

    File file = null;
    String path = "";
    JFileChooser chooser = new JFileChooser();
    chooser.addChoosableFileFilter(new ImageFileFilter());
    int returnVal = chooser.showOpenDialog(null);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        path = file.getPath();

        repaint();

    }

}                                        

class ImageFileFilter extends FileFilter {

    public boolean accept(File file) {
        if (file.isDirectory()) {
            return false; //or ur code what file u want to return
        }}

2
你能再详细解释一下你的解决方案吗?这不是一个SSCCE,我也看不出与原始代码的关系... - ncenerar
1
我是Java的新手,我在NetBeans中创建了一个应用程序来浏览文件并保存它们。我尝试了这段代码,它让我也可以创建一个新文件夹,所以我建议使用这段代码 :) 如果有帮助的话,如果没有,我很抱歉。 - Shiv
这样做是不行的,它应该调用 showSaveDialog,否则用户将无法输入新文件名。 - Edoardo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接