【发布时间】:2018-06-23 03:46:21
【问题描述】:
我正在尝试编写一个程序,它会提示用户选择一个文件夹,然后允许用户显示该文件夹中的所有内容。我一直在网上搜索,发现了几个使用 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 ");
}
}
}
【问题讨论】:
-
你可以试试
chooser.showOpenDialog(new javax.swing.JFrame());
标签: java swing jfilechooser