简体   繁体   English

空指针异常-Netbeans GUI项目

[英]Null Pointer Exception- Netbeans gui project

I keep getting this error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException, when I run my program and click on any of the jbuttons I created. 我不断收到此错误:运行程序并单击我创建的任何jbutton时,线程“ AWT-EventQueue-0” java.lang.NullPointerException中的异常。 How can I fix my code so that it will create my images? 如何修复我的代码,以便它可以创建我的图像?

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
*/

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

/**
 *
 * @author Sara
 */
public class NewJFrame extends javax.swing.JFrame {

private static BufferedImage img;



/**
 * Creates new frame
 */
public NewJFrame() {
    initComponents();
}

/**
 * makes normal clothes
 */
public void normal(){
    try {
        img = ImageIO.read(new File("Nguyen_normal.png"));
    } catch (IOException e) {
    }
    jLabel2.setIcon(new ImageIcon(img));

}

/**
 * makes dress 1
 */
public void dress1() {

    try {
        img = ImageIO.read(new File("Nguyen_black_dress.png"));
    } catch (IOException e) {
    }
    jLabel2.setIcon(new ImageIcon(img));
}

/**
 * makes dress 2
 */
public void dress2() {

    try {
        img = ImageIO.read(new File("Nguyen_blue_dress.png"));
    } catch (IOException e) {
    }
        jLabel2.setIcon(new ImageIcon(img));
}

/**
 *makes dress 3
 */
public void dress3() {

    try {
        img = ImageIO.read(new File("Nguyen_cap_dress.png"));
    } catch (IOException e) {
    }
         jLabel2.setIcon(new ImageIcon(img));
}

/**
 * makes dress 4
 */
public void dress4() {

    try {
        img = ImageIO.read(new File("Nguyen_green_dress.png"));
    } catch (IOException e) {
    }
         jLabel2.setIcon(new ImageIcon(img));
}

/**
 * makes dress 5
 */
public void dress5() {

    try {
        img = ImageIO.read(new File("Nguyen_in_pink.png"));
    } catch (IOException e) {
    }
     jLabel2.setIcon(new ImageIcon(img));
}

/**
 * makes dress 6
 */
public void dress6() {

    try {
        img = ImageIO.read(new File("Nguyen_long_gown.png"));
    } catch (IOException e) {
    }
         jLabel2.setIcon(new ImageIcon(img));
}

/**
 * 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();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jPanel2 = new javax.swing.JPanel();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();
    jButton5 = new javax.swing.JButton();
    jButton6 = new javax.swing.JButton();
    jButton7 = new javax.swing.JButton();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setMaximumSize(new java.awt.Dimension(650, 400));
    jPanel1.setMinimumSize(new java.awt.Dimension(601, 349));

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(668, 668, 668)
                    .addComponent(jLabel1))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(219, 219, 219)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(132, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(18, 18, 18)
            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 603, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jLabel1))
    );

    jLabel2.getAccessibleContext().setAccessibleParent(jLabel1);

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

    jButton3.setText("Dress Two");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    jButton4.setText("Dress Three");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }
    });

    jButton5.setText("Dress Four");
    jButton5.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton5ActionPerformed(evt);
        }
    });

    jButton6.setText("Dress Five");
    jButton6.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton6ActionPerformed(evt);
        }
    });

    jButton7.setText("Dress Six");
    jButton7.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton7ActionPerformed(evt);
        }
    });

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

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(1398, 1398, 1398))
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGap(55, 55, 55)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(29, 29, 29)
            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(26, 26, 26)
            .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    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()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap())
    );

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

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    dress1();
}                                        

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    dress2();
}                                        

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    dress5();
}                                        

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    dress3();
}                                        

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    dress4();
}                                        

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    dress6();
}                                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    normal();
}                                        

/**
 * @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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(() -> {
        new NewJFrame().setVisible(true);
    });
}
// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
// End of variables declaration                   
}

The files are in the same folder as my NewJFrame class 这些文件与我的NewJFrame类位于同一文件夹中

This automatically suggest that the images are, what is commonly known as, embedded resources. 这自动提示图像是通常所说的嵌入式资源。 Remember, a class lives in a package, which can live inside a Jar file. 请记住,一个类位于一个包中,该包可以位于一个Jar文件中。 This makes accessing these resources different from accessing resources on the file system... 这使得访问这些资源不同于访问文件系统上的资源。

Instead of using ImageIO.read(new File("Nguyen_black_dress.png")); 而不是使用ImageIO.read(new File("Nguyen_black_dress.png")); you should be using something like Class#getResource(...) , for example.. 例如,您应该使用类似Class#getResource(...)东西。

try {
    img = ImageIO.read(getClass().getResource("Nguyen_black_dress.png"));
} catch (IOException e) {
    e.printStackTrace();
}

Reading images each time you want to display them is inefficient, you may not see too much of an issue with something simple like this, but trust us when we say, this is not a good habit to get into. 每次想要显示图像时阅读图像的效率都很低,您可能不会觉得像这样简单的事情有太多问题,但是当我们说这不是一个养成的好习惯时,请相信我们。

Consider loading the images when the class is instantiate and storing them in a Map of some kind for easy retrieval, for example... 考虑在实例化类时加载图像,并将其存储在某种Map中以便于检索,例如...

private Map<String, BufferedImage> mapImages;
//...
mapImages = new HashMap<>(25);
mapImages.put("normal", ImageIO.read(new File("Nguyen_normal.png")));

Then when you want to the "normal" image, simply retrieve it from the Map ... 然后,当您想要“正常”图像时,只需从Map检索它即可...

BufferedImage normal = mapImages.get("normal");

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM