-1

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. 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                   
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
saybe
  • 1
  • 1
    The fact that you're ignoring any exceptions thrown by `ImageIO` suggests at least one potential issue. Starting by adding (at the very least) `e.printStackTrace()` in the `catch` block of the `try-catch` statement and see what the actual error is – MadProgrammer Jun 02 '14 at 02:43
  • I think that *is* the issue. Be careful about blindly ignoring exceptions and be sure that your references are instantiated before attempting to call methods on them. – Makoto Jun 02 '14 at 02:44
  • 2
    @Makoto Yes, but the issue is likely that the images aren't been loaded because they should be treated as embedded resources, the duplicate question, IMHO, is too broad for the specific case – MadProgrammer Jun 02 '14 at 02:46
  • 1
    In that case...I'll let it be. To saybe: It would be extremely helpful if you provided the stack trace(s) as to where this is occurring. Or better yet, make sure that those images exist exactly in the same location as your Java code, or it won't pick them up. – Makoto Jun 02 '14 at 02:47
  • Aside: you shouldn't be trying to read new images based off some action. Instead read in all the images at application launch, in to some holder, then just set the icon accordingly based off the actions. – Paul Samsotha Jun 02 '14 at 02:48
  • The files are in the same folder as my NewJFrame class, this is my first time attempting any form of gui, that being said, I'm very confused. When I put in the e.printStackTrace() it said it couldn't read the input file, so that was the problem. How do I read the images at launch? – saybe Jun 02 '14 at 02:54
  • 1
    Read your images in your class's constructor and put the images in fields. Also, you should almost never ignore exceptions. Also, if this were my assignment and I were stuck, I'd first test out reading and display a single image in a very simple program, and then work the bugs out of this program before using the techniques in my larger more complex program. – Hovercraft Full Of Eels Jun 02 '14 at 02:58
  • 2
    God God! It took you almost 350 LOC before you realized you could not load an image?!? Try it first in an app. with 50 LOC. BTW - By the time of deployment, those resources will likely become an [tag:embedded-resource]. That being the case, the resource must be accessed by `URL` instead of `File`. See the [info page](http://stackoverflow.com/tags/embedded-resource/info) for the tag, for a way to form an `URL`. – Andrew Thompson Jun 02 '14 at 02:58
  • 1
    @AndrewThompson and I are saying essentially the same thing, though in a different style, so to speak. – Hovercraft Full Of Eels Jun 02 '14 at 02:59

1 Answers1

3

The files are in the same folder as my NewJFrame class

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. This makes accessing these resources different from accessing resources on the file system...

Instead of using ImageIO.read(new File("Nguyen_black_dress.png")); you should be using something like Class#getResource(...), for example..

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...

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...

BufferedImage normal = mapImages.get("normal");
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366