有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    如果您不在目录中,则文件名将不起作用,因为文件将在打开的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文档的信息