我利用一个JFileChooser的程序。 要简短,完整的程序是一个图形用户界面,允许用户操作PNG格式和JPG格式。 我想,这样JFileChooser中立即打开图片目录(窗口)做出来。 当用户打开他们的JFileChooser中,它会直接开到图片库C:\ Users \(用户)\图片
此外,这将是很好,只显示特定类型(PNG格式和JPG格式)的文件。 许多程序似乎是能够做到这一点; 只允许特定文件的选择。 JFileChooser的是否允许这样的事情? 目前,我使用的是大量不可靠的,周围的方法运行拒绝非的PNG / JPG图片。
下面指的是图形用户界面,其中用户将选择其用于编辑图片,并将其显示在屏幕上的“浏览”按钮。
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();
}
谢谢。