简体   繁体   English

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

[英]Getting a NullPointerException when trying to open an image file in java

I have a memory match program that allows users to add new folders and and images into them. 我有一个内存匹配程序,允许用户向其中添加新的文件夹和图像。 When the program runs with the default folder and images it works fine. 当程序使用默认文件夹和图像运行时,它可以正常工作。 When it selects the user added folder it gets to the point where it adds the first image and then gives a NullPointerException . 当选择用户添加的文件夹时,它将到达添加第一个图像的位置,然后给出NullPointerException

Here is the code where I think the problem is 这是我认为问题所在的代码

    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());

The next line is where the NullPointerException is at 下一行是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);

As stated this code works fine when I use the default folder it only breaks when it attempts to use user supplied images. 如前所述,当我使用默认文件夹时,此代码工作正常,只有在尝试使用用户提供的图像时,它才会中断。

Here is the code that creates the directory: 这是创建目录的代码:

    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);

Here is the code that saves the image 这是保存图像的代码

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());
    }

The save creates a new file in the folder selected by the user. 保存将在用户选择的文件夹中创建一个新文件。 The game even sees the file as it will enter the if statement and print the message I added in. But at that point it gives the exception. 游戏甚至看到该文件,因为它将输入if语句并打印我添加的消息。但是在那时,它给出了异常。

I forgot to say that the message printed just before the exception is showing the expected path images/userfolder/userimage.png. 我忘了说在异常发生之前打印的消息显示了预期的路径images / userfolder / userimage.png。

This code: 这段代码:

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

... relies on the image being available as a resource in the same classloader as the executing class. ...依赖于与执行类在同一类加载器中的图像可用作资源。 If it's just a file on the file system and the class is in a jar file, that won't be the case. 如果它只是文件系统上的一个文件,并且该类位于jar文件中,则情况并非如此。

If you're just trying to load a file, don't use Class.getResource() - just pass the filename (ideally an absolute filename to avoid any ambiguity) to the ImageIcon constructor. 如果您只是想加载文件,请不要使用Class.getResource() -只需将文件名(最好是绝对文件名,以避免任何歧义)传递给ImageIcon构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试打开ZXingScannerView时发生NullPointerException - NullPointerException when trying to open ZXingScannerView 在 Java 中,为什么我在尝试显示 FileNotFoundException 时会收到 NullPointerException? - In Java, why am I getting a NullPointerException when trying to display a FileNotFoundException? 尝试在webDriver中使用@FindBy时获取java.lang.NullPointerException - Getting java.lang.NullPointerException when trying to use @FindBy in webDriver 尝试在Java中读取txt文件时出现java.lang.NullPointerException - java.lang.NullPointerException when trying to read txt file in java 尝试将文件写入内部数据时不断获取NullPointerException - Keep getting NullPointerException when trying to write file to internal data 为什么我在尝试读取文件时收到 NullPointerException? - Why am I getting a NullPointerException when trying to read a file? 尝试显示图像时出现NullPointerException? - NullPointerException when trying to display image? 尝试显示.gif文件时出现java.lang.NullPointerException? - java.lang.NullPointerException when trying to display a ,gif file? 尝试逐行读取文件(Java)时出现NullPointerException? - NullPointerException when trying to read a file line by line (Java)? Opentimestamps - 尝试反序列化 OTS 文件时出现 Java NullPointerException - Opentimestamps - Java NullPointerException when trying to deserialize OTS file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM