簡體   English   中英

JFileChooser showSaveDialog在文件名為空或為空時顯示錯誤消息

[英]JFileChooser showSaveDialog show an error message when file name is blank or empty

該代碼可用於檢查非空/空格的AbsolutePath,但不適用於AbsolutePath僅為空白的情況。 單擊保存不執行任何操作,並且JFileChooser停留在showSaveDialog()中。

當用戶嘗試使用空白文件名保存文件時,我想顯示JOptionPane錯誤消息。

    try {
        JFileChooser chooser = new JFileChooser("./");
        FileNameExtensionFilter filter = new FileNameExtensionFilter("files (txt)", "txt");
        chooser.setFileFilter(filter);
        chooser.setMultiSelectionEnabled(false);
        chooser.setSelectedFile(new File(fileName));

        int value = chooser.showSaveDialog(this);
        if (value == JFileChooser.APPROVE_OPTION) {
            String filename = chooser.getSelectedFile().getAbsolutePath();
            if (chooser.getSelectedFile().getName().trim().equals("")
                    || !chooser.getSelectedFile().getName().endsWith(".txt")
                    || chooser.getSelectedFile().getName().replaceAll(".txt", "").trim().equals("")) {
                throw new IllegalArgumentException();
            }
            saveFile(filename);
        }

    } catch (IllegalArgumentException e) {
        JOptionPane.showMessageDialog(this, "Fail! File was not saved", "Error", JOptionPane.ERROR_MESSAGE);
    }

Clicking save does nothing and the JFileChooser stays in showSaveDialog(). 正如@camickr上面所說的: this is the built in functionality of the JFileChooser and has nothing to do with your code. The file chooser doesn't close unless you enter a filename (and click Save) or use the Cancel button. this is the built in functionality of the JFileChooser and has nothing to do with your code. The file chooser doesn't close unless you enter a filename (and click Save) or use the Cancel button.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM