JFileChooser.showSaveDialog(…) - how to set suggested file name

前端 未结 3 1116
后悔当初
后悔当初 2020-11-30 04:43

The JFileChooser seems to be missing afeature: a way to suggest the file name when saving a file (the thing that usually gets selected so that it would get repl

3条回答
  •  天命终不由人
    2020-11-30 05:02

    setSelectedFile doesn't work with directories as mentioned above, a solution is

        try {
            FileChooserUI fcUi = fileChooser.getUI();
            fcUi.setSelectedFile(defaultDir);
            Class fcClass = fcUi.getClass();
            Method setFileName = fcClass.getMethod("setFileName", String.class);
            setFileName.invoke(fcUi, defaultDir.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    

    Unfortunately the setFileName is not included in the UI interface, thus the need to call it dynamically. Only tested on mac.

提交回复
热议问题