簡體   English   中英

嘗試在Java中打開圖像文件時獲取NullPointerException

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

我有一個內存匹配程序,允許用戶向其中添加新的文件夾和圖像。 當程序使用默認文件夾和圖像運行時,它可以正常工作。 當選擇用戶添加的文件夾時,它將到達添加第一個圖像的位置,然后給出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。

這段代碼:

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

...依賴於與執行類在同一類加載器中的圖像可用作資源。 如果它只是文件系統上的一個文件,並且該類位於jar文件中,則情況並非如此。

如果您只是想加載文件,請不要使用Class.getResource() -只需將文件名(最好是絕對文件名,以避免任何歧義)傳遞給ImageIcon構造函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM