如何避免 .getSelectedFile() 过早选择?

huangapple go评论74阅读模式
英文:

How to avoid .getSelectedFile() premature selection?

问题

似乎 .getSelectedFile() 函数在选择取消选项后仍然会选择文件选择器中的文件夹。是否有不同的函数可用?比如 getOpenedFolder(),也许?我会感激任何帮助。以下是我的代码:

fc = new JFileChooser();
boolean flag = false;
fc.setCurrentDirectory(new java.io.File("C:/Users/michaelartichoke/Desktop"));
fc.setDialogTitle("PDF Manager");
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(null);

chosenfolder = fc.getSelectedFile();
try {
    folderpath = chosenfolder.getAbsolutePath();
    flag = true;
} catch (Exception e) {
    //
}

if (flag != false) {
    selecting();
}

顺便说一下,selecting() 是创建数据库的命令。

英文:

It appears that the .getSelectedFile() functions will still choose a folder from a file chooser even after choosing the cancel option. Is there a different function? Like getOpenedFolder(), maybe? I would appreciate any help. Here is my code: <br/>

        boolean flag = false;
        fc.setCurrentDirectory(new java.io.File(&quot;C:/Users/michaelartichoke/Desktop&quot;));
        fc.setDialogTitle(&quot;PDF Manager&quot;);
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.showOpenDialog(null);
        
        chosenfolder = fc.getSelectedFile();
        try{
            folderpath = chosenfolder.getAbsolutePath();
            flag = true;
        } catch(Exception e){
            //
        }
        
        if(flag!=false){
            selecting();
        }

FYI, selecting() is the command that creates the database.

答案1

得分: 1

你需要查看showOpenDialog()返回的结果,以确定用户是否选择了“打开”:

int res = fc.showOpenDialog(null);
if (res == JFileChooser.APPROVE_OPTION) {
    // 用户选择了“打开”
    chosenfolder = fc.getSelectedFile();
    // ...
}
英文:

You need to look at the result that showOpenDialog() returned to see if the user chose "Open":

int res = fc.showOpenDialog(null);
if (res==JFileChooser.APPROVE_OPTION) {
    // User picked &#39;Open&quot;
    chosenfolder = fc.getSelectedFile();
    // ...
}

huangapple
  • 本文由 发表于 2020年9月13日 21:50:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63871554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定