3

我正在尝试创建从组合框中选择时显示颜色的小框。但是当我尝试运行程序时,我不断收到 NullPointerException 错误。我看不出它有什么问题。

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)
4

3 回答 3

3

你的问题是你还没有初始化picture。你有

private JLabel picture;

但这从未设置过:

 picture.setIcon(...);

在构造函数中调用,尽管是在一个条件内。

你需要初始化它,例如

picture = new JLabel(...); // whatever
于 2013-04-14T12:05:55.440 回答
2

picture您在初始化对象之前正在使用它。

利用

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

初始化

picture = new JLabel(pics[0]);

将初始化语句移到侦听器上方。

于 2013-04-14T12:10:10.803 回答
1

picture我会在您声明后立即尝试初始化。

因此,不要使用private JLabel picture;尝试使用:

private JLabel picture = new JLabel(pics[0]);

于 2013-04-15T05:57:21.193 回答