你知道,我有使用 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/