我正在编写一个程序,它将提示用户选择一个文件夹,然后允许用户显示文件夹中的所有内容。我一直在搜索webs,并找到了几个使用JFileChooser的例子,包括这个here。当我试图在JGrasp中使用上一个链接中的示例时,它将运行而不会出现问题。然而,当我试图在NetBeans中运行它时,我会得到错误( DemoJFileChooser类不会编译,因为需要返回类型,Main中的行说找不到符号DemoJFileChooser)。我不知道它有什么问题,但我已经尽我所能地调整了它
下面的程序编译并运行良好,但是当我选择选项1时,程序只会冻结一秒钟,然后重新显示菜单。我无法让它显示文件选择对话框。我做错了什么?
import java.util.Scanner;
import javax.swing.JFileChooser;
public class FileDirectoryProcessing {
JFileChooser chooser;
String choosertitle;
public static void main(String[] args) {
SelectionMenu:
while (true) {
Scanner scannerIn = new Scanner(System.in);
System.out.println("0 - Exit");
System.out.println("1 - Select Directory");
System.out.println("2 – List directory contents");
System.out.println("Select Option");
try{
int userInput = Integer.parseInt(scannerIn.nextLine());
switch (userInput) {
case 0:
System.out.println("Thank you");
break SelectionMenu;
case 1:
System.out.println("Select a directory");
new FileDirectoryProcessing().ChooseDirectory();
break;
case 2:
System.out.println("Directory Contents");
break;
default:
System.out.println("Please make a valid selection");
break;
}
} catch (NumberFormatException e){
System.out.println("Please make a valid selection");
}
}
}
private void ChooseDirectory(){
chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
System.out.println(chooser.getCurrentDirectory()
+ "getCurrentDirectory(): ");
System.out.println("getSelectedFile() : "
+ chooser.getSelectedFile());
}
else {
System.out.println("No Selection ");
}
}
}发布于 2018-06-23 03:57:30
方法showOpenDialog接受组件,而this (FileDirectoryProcessing实例)不是组件,因此出现了问题。
在方法中提供父component实例。或者现在也可以传递chooser (JFileChooser的实例)或null。
因此,以下两个选项都可以正常工作:
chooser.showOpenDialog(chooser)或
chooser.showOpenDialog(null)https://stackoverflow.com/questions/50997770
复制相似问题