无法从文件夹导入图像的随机路径? (JAVA)

时间:2016-01-21 17:38:28

标签: java nullpointerexception

我不明白我的代码有什么问题..程序运行正常,直到我使用“randPath()”方法执行它。我总是得到这个错误:

线程中的异常“AWT-EventQueue-0”java.lang.NullPointerException

我的代码如下:

package org.me.mycardapp;

import java.io.File;
import java.util.Random;

public class CardDisplay extends javax.swing.JFrame {
public CardDisplay() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jPanel2 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

    jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
    jPanel2.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            jPanel2MousePressed(evt);
        }
    });

    jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/me/mycardapp/newpackage/10_of_diamonds.png"))); // NOI18N

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(267, 267, 267)
            .addComponent(jLabel1)
            .addContainerGap(343, Short.MAX_VALUE))
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(24, 24, 24)
            .addComponent(jLabel1)
            .addContainerGap(47, Short.MAX_VALUE))
    );

    jButton1.setText("Change");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton1)
            .addGap(343, 343, 343))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    jButton2.setText("Exit");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(jButton2)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton2)
            .addGap(5, 5, 5))
    );

    pack();
}// </editor-fold>                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    System.exit(0);
}                                        

private void jPanel2MousePressed(java.awt.event.MouseEvent evt) {                                     
    jLabel1.setLocation(evt.getX()-63, evt.getY()-91);
}                                    

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(randPath())));
}                                        

public String randPath () {
    Random rand = new Random();
    String path;
    File file = new File("/org/me/mycardapp/newpackage/");
    File[] files = file.listFiles();
    int r = rand.nextInt(files.length);
    path = files[r].getPath();
    return path;
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(CardDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(CardDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(CardDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(CardDisplay.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new CardDisplay().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
// End of variables declaration                   

}

3 个答案:

答案 0 :(得分:0)

您的问题出现在randPath字符串中的这一行。

File file = new File("/org/me/mycardapp/newpackage/");

将其更改为以下行,它应解决问题

File file = new File("org/me/mycardapp/newpackage/");

修改

运行您提供的代码后,我发现了异常。问题是您的代码如下所示。

getClass().getResource(...))

您有两种选择。 If you are using an IDE such as Eclipse and don't want to change code go for Option 2

选项1

更改

jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/me/mycardapp/newpackage/10_of_diamonds.png"))); // NOI18N

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(randPath())));
}

jLabel1.setIcon(new javax.swing.ImageIcon("org/me/mycardapp/newpackage/10_of_diamonds.png")); // NOI18N

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jLabel1.setIcon(new javax.swing.ImageIcon(randPath()));
}

选项2

观看this video,它解释了如何在Eclipse等IDE中解决问题。

通过这种方式,您可以将代码保持为相同,只需将图片放入包中,如视频所示

注意:很抱歉,一个相当小的孩子提出它但是因为他解释得很好而提高音量

答案 1 :(得分:0)

尝试编写确切的目录。而不是"/org/me/mycardapp/newpackage/"尝试此"c:/.../org/me/mycardapp/newpackage/"。填补点。

答案 2 :(得分:0)

有两种方法:

 File file = new File("c:/.../org/.."); // enter the exact path
String[] files = file.list();
int r = rand.nextInt(files.length);
path = file.getPath()+File.separatorChar+files[r];
 File file = new File("c:/.../org/.."); // enter the exact path
File[] files = file.listFiles();
int r = rand.nextInt(files.length);
path = files[r].getPath();