java - 按钮取消 JFileChooser 单击时仍加载文件

标签 java swing filechooser

你知道,我有使用 JFileChooser 选择文件的按钮。这是我的代码

private void buttonFIleBrowserInPanelActionPerformed(java.awt.event.ActionEvent evt) {                                                         
    try {

        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Please, choose your main file ... ");

        chooser.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".java") || f.isDirectory();
            }

            @Override
            public String getDescription() {
                return "Java File (*.java)";
            }
        });
        chooser.setAcceptAllFileFilterUsed(true);
        chooser.showOpenDialog(null); 

        File f = chooser.getCurrentDirectory();
        File ff = chooser.getSelectedFile();
        mainFile = ff;
        if (ff != null) { 
            nameFile = ff.toString();

            File namaFilenya = new File(nameFile);
            try {
                FileReader readFile = new FileReader(namaFilenya);
                String readFileToString = readFile.toString();

                try {
                    txtFile.read(readFile, null); // this is the textArea that show the contains of file
                    txtPathMainFile.setText(nameFile); //this is the textarea that show the path of file

                } catch (IOException ex) {
                    System.out.println(ex);
                }

            } catch (FileNotFoundException ex) {
                System.out.println(ex);

            }

        }
    } catch (Exception e) {
    }
}

当我单击选择器中的一个文件然后单击“确定”时,它成功加载了我需要的所有内容。但是,在另一种情况下,当我单击文件但决定选择取消时,文件仍然加载在我的文本区域中。如何解决这个问题?

最佳答案

检查 JFileChooser 的响应.

示例代码:

int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
   // rest your code goes here
}

您可以检查CANCEL_OPTION也是如此。

有关使用 JFileChooser 的信息,请参阅 How to Use File Choosers ,《Java 教程》中的一节。

关于java - 按钮取消 JFileChooser 单击时仍加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24841292/

相关文章:

java - 设置 JavaFX FileChooser 的初始目录

html - 不使用 <input type ="file"/> 的自定义文件选择器

java - 从动态创建的 JTextFields 获取内容

java - 如何从换行符中给出的api获取数据

java - 无法从 PMD 中排除某些规则

java - 为什么实例化 JavaFX 场景控件会破坏布局

java - JFrame内容未完全显示

java - 如何强制不同分辨率的字体大小相同(以 px 为单位)

JavaFX FileChooser Filefilter 不返回扩展名

java - 沙盒 JSR-223