Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException, killed my program

I'm trying to create my little box that shows the color when selected from the combo box. But I keep getting this error of NullPointerException when I try to run the program. I don't see what is wrong with it.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ThreeColorsFrame extends JFrame
{
    private static final int FRAME_WIDTH = 300;
    private static final int FRAME_HEIGHT = 400;

    private JComboBox box;
    private JLabel picture;

    private static String[] filename = { "Red", "Blue", "Green" };
    private Icon[] pics = { new ImageIcon(getClass().getResource(filename[0])),
                    new ImageIcon(getClass().getResource(filename[1])),
                    new ImageIcon(getClass().getResource(filename[2])) };

    public ThreeColorsFrame()
    {
        super("ThreeColorsFrame");
        setLayout(new FlowLayout());

        box = new JComboBox(filename);

        box.addItemListener(new ItemListener()
        {
            public void itemStateChanged(ItemEvent event)
            {
                if (event.getStateChange() == ItemEvent.SELECTED)
                    picture.setIcon(pics[box.getSelectedIndex()]);
            }
        });

        add(box);
        picture = new JLabel(pics[0]);
        add(picture);

    }

}

Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at ThreeColorsFrame.<init>(ThreeColorsFrame.java:33)
    at ThreeColorsViewer.main(ThreeColorsViewer.java:36)
like image 391
Elizabeth Turner Avatar asked Sep 12 '26 11:09

Elizabeth Turner


2 Answers

Your problem is you haven't initialized picture. You have

private JLabel picture;

But this never gets set before:

 picture.setIcon(...);

is called in the constructor, albeit within a condition.

You need to initialize it, eg

picture = new JLabel(...); // whatever
like image 100
Bohemian Avatar answered Sep 15 '26 02:09

Bohemian


You are using picture object before you have initialized it.

USE

picture.setIcon(pics[box.getSelectedIndex()]);

INITIALIZATION

picture = new JLabel(pics[0]);

Move the initialization statement above the listener.

like image 39
kaysush Avatar answered Sep 15 '26 02:09

kaysush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!