如何通过连接文件名来使用JFileChooser打开文件

时间:2018-05-05 20:11:50

标签: java jfilechooser

我只能在JFileChooser中写文件的名称来打开文件,除非我和它在同一个文件夹中,我该怎么办才能修复它?

    JDialog.setDefaultLookAndFeelDecorated(true);
                if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                    FileFilter imageFilter = new FileNameExtensionFilter("Image files", ImageIO.getReaderFileSuffixes());
                    chooser.setFileFilter(imageFilter);
                    File file = chooser.getSelectedFile();
                    String filePath = file.getAbsolutePath();
                    icon = new ImageIcon(filePath);
                    try{
                        original = ImageIO.read(file);
                        image = ImageIO.read(file);
                        width = image.getWidth();
                        height = image.getHeight();
                        if (width > 1000 && height > 1000){
                            image = null;
                            JOptionPane.showMessageDialog(null, "Image is too big (maximum 1000px by 1000px)", "Message: ", JOptionPane.INFORMATION_MESSAGE);
                        } else if (width > 1000 && height <= 1000) {
                            image = null;
                            JOptionPane.showMessageDialog(null, "Width is too big (maximum 1000px)", "Message: ", JOptionPane.INFORMATION_MESSAGE);
                        } else if (width <= 1000 && height > 1000) {
                            image = null;
                            JOptionPane.showMessageDialog(null, "Height is too big (maximum 1000px)", "Message: ", JOptionPane.INFORMATION_MESSAGE);
                        }
                    } catch (IOException e) {
                        System.out.println(e);
                    }

                    picture = new ImageIcon(image);
                    label.setIcon(picture);
                }

1 个答案:

答案 0 :(得分:0)

如果您不在目录中,则文件名将不起作用,因为将在打开的JFileChooser的当前目录中搜索该文件。您需要为JFileChooser提供文件的完整绝对路径,而不仅仅是文件名

注意:我只是在Notepad ++中模拟它只是说无法找到文件名,因此您可以在其他操作之前检查文件是否存在,将此代码段添加到您的代码中

JDialog.setDefaultLookAndFeelDecorated(true);
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        FileFilter imageFilter = new FileNameExtensionFilter("Image files", ImageIO.getReaderFileSuffixes());
        chooser.setFileFilter(imageFilter);
        File file = chooser.getSelectedFile();
        if (!file.exists()) {
           JOptionPane.showMessageDialog(null, "The file "+file.getName()+"\ncannot be found !!!", JOptionPane.INFORMATION_MESSAGE);
           showDialogAgain();
        } else {
          String filePath = file.getAbsolutePath();
          icon = new ImageIcon(filePath);
          ...
        }
    }
    ...

详细了解JFileChooser文档