尝试在java中打开图像文件时获取NullPointerException

时间:2013-12-15 21:20:24

标签: java nullpointerexception

我有一个内存匹配程序,允许用户在其中添加新文件夹和图像。当程序使用默认文件夹和图像运行时,它可以正常工作。当它选择用户添加的文件夹时,它会到达添加第一个图像的点,然后给出NullPointerException

以下是我认为问题所在的代码

    ArrayList <Card> cardsList = new ArrayList();

    //cboDifficulty.addActionListener(this);
    String difficulty =  cboDifficulty.getSelectedItem().toString();

        gameDiff = 0;//initialize gameDiff to 0

    if(difficulty.equals("Beginner")){//Beginnner
    /*place 3 cards and 1 copy of each card (total of 6 cards) on gamescreen*/
        gameDiff = 3;
    }
    else if(difficulty.equals("Easy")){//Easy
    /*place 6 cards and 1 copy of each card (total of 12 cards) on gamescreen*/
        gameDiff = 6;
    }

    String userDir = cboImages.getSelectedItem().toString();
    File filePath = new File(baseDir + "/" + userDir + "/");

    comboFile =  filePath.listFiles();


    List<File> listShuffle = Arrays.asList(comboFile);
    Collections.shuffle(listShuffle);
    for(int tick = 0; tick < listShuffle.size(); tick++){
        comboFile[tick] = listShuffle.get(tick);
    }

    for(int ctr = 0; ctr < comboFile.length; ctr++){
        if(ctr < gameDiff){

            Card card = new Card();
            card.setbackImage(new ImageIcon(cardBackImage));

            Image img = null;

            if(comboFile[ctr].isFile()){
                JOptionPane.showMessageDialog(null, comboFile[ctr].toString());

下一行是NullPointerException所在的位置

                img = new ImageIcon(this.getClass().getResource(comboFile[ctr].getPath())).getImage();
            }

            Image dimg = img.getScaledInstance(144, 216, Image.SCALE_SMOOTH);
            card.setfrontImage(new ImageIcon(dimg));

            // Populate card with db results
            cardsList.add(card);

        }

    }
        // Clone list of cards for game
        for(int counter = 0; counter < gameDiff && counter < cardsList.size(); counter++){
            // Pull out current card from the loop
            Card orgCard = cardsList.get(counter);


            // Make new card to populate (clone it)
              Card cloneCard =  new Card();
              cloneCard.setfrontImage(orgCard.getfrontImage());
              cloneCard.setbackImage(orgCard.getbackImage());

              cardsList.add(cloneCard);

          }                   

    shuffleCard(cardsList);

    createGameScreen(cardsList);

如上所述,当我使用默认文件夹时,此代码工作正常,只有在尝试使用用户提供的图像时它才会中断。

以下是创建目录的代码:

    JFileChooser fc = new JFileChooser();


    int returnVal = fc.showOpenDialog(null);

    fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);
    if (returnVal == fc.APPROVE_OPTION) {
        File selectedFile = fc.getSelectedFile();
        imageFilename = selectedFile.getPath();
        JOptionPane.showMessageDialog(null, "You selected " + imageFilename);
        ImageIcon imageView = new ImageIcon(imageFilename);
        lblIcon.setIcon(imageView);

以下是保存图像的代码

String sveCaption = lblCaption.getText();


    // Convert text in combobox to string...
    String newDir = cboSelectGroup.getSelectedItem().toString();

    // Convert path to string...
    String src = baseDir + "/" + newDir;

    // Create new file...
    File javaFilePath = new File(src, "/" + lblCaption.getText() + ".png");
    File oldImage = new File(imageFilename);
    if (! javaFilePath.exists()){

        JOptionPane.showMessageDialog(null, "Folder/Category, Image and Caption saved!!!");
        //oldImage.renameTo(javaFilePath);
        FileChannel copyFile = new FileInputStream(oldImage).getChannel();
        FileChannel dest = new FileOutputStream(javaFilePath).getChannel();
        dest.transferFrom(copyFile, 0, copyFile.size());
    }

保存会在用户选择的文件夹中创建一个新文件。游戏甚至会看到文件,因为它将进入if语句并打印我添加的消息。但在那时它会给出异常。

我忘了说在异常之前打印的消息显示了预期的路径images / userfolder / userimage.png。

1 个答案:

答案 0 :(得分:3)

此代码:

this.getClass().getResource(comboFile[ctr].getPath())

...依赖于可用作与执行类相同的类加载器中的资源的图像。如果它只是文件系统上的一个文件而且该类在一个jar文件中,则不会出现这种情况。

如果您只是尝试加载文件,请不要使用Class.getResource() - 只需将文件名(理想情况下是绝对文件名以避免任何歧义)传递给ImageIcon构造函数