java swing nullpointerexception jcombobox

java - NullPointerException, mató a mi programa



swing jcombobox (3)

Intento crear mi pequeña caja que muestra el color cuando se selecciona desde el cuadro combinado. Pero sigo recibiendo este error de NullPointerException cuando intento ejecutar el programa. No veo lo que está mal con eso.

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)


Está utilizando un objeto de picture antes de haberlo inicializado.

UTILIZAR

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

INICIALIZACIÓN

picture = new JLabel(pics[0]);

Mueva la declaración de inicialización por encima del oyente.


Su problema es que no ha inicializado la picture . Tienes

private JLabel picture;

Pero esto nunca se establece antes:

picture.setIcon(...);

se llama en el constructor, aunque dentro de una condición.

Necesita inicializarlo, por ej.

picture = new JLabel(...); // whatever


Intentaría inicializar la picture tan pronto como la declarara.

Entonces, en lugar de usar private JLabel picture; tratar de usar:

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