我有一个程序使用JFileChooser。简而言之,完整的程序是一个GUI,它允许用户操纵PNG和JPG。我想让JFileChooser立即打开图片目录(窗口)。当用户打开他们的JFileChooser时,它会直接打开图片库C:\ Users \(USER)\图片在指定的目录启动JFileChooser,只显示特定类型的文件
此外,只显示特定类型的文件(PNG和JPG)会很好。许多程序似乎都能够做到这一点;只允许选择特定的文件。 JFileChooser是否允许这样的事情?目前,我正在使用大规模不可靠的运行方法来拒绝非PNG/JPG。
以下内容是指GUI的“浏览”按钮,用户在其中选择要编辑的图片并将其显示在屏幕上。
try {
int val = filec.showOpenDialog(GridCreator.this);
if(val==JFileChooser.APPROVE_OPTION) {
File unfiltered_picture = filec.getSelectedFile();
//get the extension of the file
extension=unfiltered_picture.getPath();
int index=extension.indexOf(".");
extension=extension.substring(index+1, extension.length());
//if the file is not jpg, png, or jpeg, reject it and send a message to the user.
if(!extension.matches("[jJ][pP][gG]") && !extension.matches("[pP][nN][gG]") && !extension.matches("[jJ][pP][eE][gG]")) {
JOptionPane.showMessageDialog(null,
"cannot load file. File must be of type png, jpeg, or jpg. \n Your file is of type " + extension,
"Error: improper file",
JOptionPane.OK_OPTION);
//if the file is of the proper type, display it to the user on the img JLabel.
} else {
finalImage = ImageIO.read(unfiltered_picture);
ImageIcon imgIcon = new ImageIcon();
imgIcon.setImage(finalImage);
img.setIcon(imgIcon);
img.invalidate();
h_divide.setValue(0);
v_divide.setValue(0);
}
}
} catch(IOException exception) {
exception.printStackTrace();
}
谢谢。
不错,但有没有办法让它直接进入C:\ Users \(user)\ Pictures目录? – corvid 2013-04-11 17:21:49
在构造函数的'new File'中指定它。代码表示“文件开始”。像新的'文件(System.getProperty(“user.home”),“图片”)'应该工作。 – 2013-04-11 17:22:56
Pictures目录的位置与系统高度相关,所以没有真正的Java方法来找到它。也就是说,您可以使用'FileSystemView'中的方法http://docs.oracle.com/javase/6/docs/api/javax/swing/filechooser/FileSystemView.html来查找用户的主目录。从那里它是一个猜谜游戏基于Windows XP/7/8/9/10/etc ... – 2013-04-11 17:24:16