0

I know it's the correct path because I ran it through the terminal. I am trying to understand JCOMBOBOX for the first time. It supersedes where I am at in my current course. I am trying to build an independent currency converter project but I want to understand some of the functionalities of swing. I found some code online to help with my understanding. If anyone can reverse engineer the sample code I found so I can better understand why I keep getting a NULL POINTER Exception when I try and introduce my .png file that would be super helpful.

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


public class Gui extends JFrame {
    private final JComboBox box;
    private final JLabel picture;

    private static String[] filename = {"/Users/christopher/Desktop/Abkhazian.png"};
    private Icon[] pics = {new ImageIcon(getClass().getResource(filename[0]))};

    public Gui(){
        super("Currency Converter");
        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);
    }

public static void main(String[] args){
        Gui go = new Gui();
        go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        go.setSize(300,200);
        go.setVisible(true);
    }
}
  • 2
    You probably have the wrong path to the resource (which the duplicate can help you with). Also, use `ImageIO.read(...)` when getting the image, and do it within a try/catch block. – Hovercraft Full Of Eels Sep 16 '21 at 23:28

0 Answers0