我正在尝试创建我的小方框,它会在从组合框中选择时显示颜色。但是当我尝试运行该程序时,我不断收到 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)
最佳答案
你的问题是你还没有初始化picture
。你有
private JLabel picture;
但这之前从未设置过:
picture.setIcon(...);
在构造函数中调用,尽管是在条件内。
你需要初始化它,例如
picture = new JLabel(...); // whatever
关于java - NullPointerException,杀死了我的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15998813/