java-NullPointerException,杀死了我的程序
作者:互联网
我正在尝试创建一个从组合框中选择颜色时显示颜色的小框.但是,当我尝试运行该程序时,我仍然收到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)
解决方法:
您的问题是您还没有初始化图片.你有
private JLabel picture;
但这从来没有设置过:
picture.setIcon(...);
尽管在条件内,但在构造函数中被调用.
您需要对其进行初始化,例如
picture = new JLabel(...); // whatever
标签:jcombobox,swing,nullpointerexception,java 来源: https://codeday.me/bug/20191031/1972379.html