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

时间:2012-12-06 07:08:52

标签: java swing file-io save jfilechooser

我可能会遗漏JFileChooser API中显而易见的内容,但当我尝试使用JFileChooser保存文件时,我只能选择要保存的预先存在的文件,而不是输入新名称并保存到该。甚至可以使用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;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

检查if条件:

if(f.exists() && getDialogType() == SAVE_DIALOG)

如果f不存在会发生什么(这是您希望的那种情况)?

你可以尝试:

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

答案 1 :(得分: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
        }}
相关问题