我有一个按钮可以使用
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
中的其中一个文件,然后单击OK
时,就成功加载了我需要的所有内容。但是,在另一种情况下,当我单击一个文件,但我决定选择 Cancel
时,该文件仍在我的 textArea
中加载。如何解决这个问题?
检查 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
返回的值。请参阅我的回答中的示例
int rv = chooser.showOpenDialog(null);
if (rv == JFileChooser.APPROVE_OPTION) {
File file= chooser.getSelectedFile();
if(fileSelected){
//load in text Area
}else{
//nothing
}
JFileChooser 实例应该返回一些布尔值。
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = chooser.getCurrentDirectory();
File ff = chooser.getSelectedFile();//
mainFile = ff;
if (ff != null) { t
nameFile = ff.toString();
File namaFilenya = new File(nameFile);
try {
FileReader readFile = new FileReader(namaFilenya);
try {
txtFile.read(readFile, null);
txtPathMainFile.setText(nameFile);
} catch (IOException ex) {
System.out.println(ex);
}
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
}
}
谢谢..