2

This is the main class:-

import javax.swing.JFrame;

public class RR {
    public static void main(String[] args) {
        RegionalResource object = new RegionalResource();
        object.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        object.setSize(500,500);
        object.setVisible(true);
    }
}

Here's the other class:-

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

public class RegionalResource extends JFrame {
    private JComboBox box;
    private JLabel picture;

    private static String imagenames[] = {"1.png", "2.png"};
    private Icon images[] = {new ImageIcon(getClass().getResource(imagenames[0])), new ImageIcon(getClass().getResource(imagenames[1])) };

    public RegionalResource() {

        super("Tourism Information Provider");
        setLayout(new FlowLayout());

        box = new JComboBox(imagenames);

        box.addItemListener(
                new ItemListener() {
                    public void itemStateChanged(ItemEvent event) {
                        if(event.getStateChange() == ItemEvent.SELECTED)
                        {
                            picture.setIcon(images[box.getSelectedIndex()]);
                        }
                    }
                }
            );
        add(box);
        picture = new JLabel(images[0]);
        add(picture);
    }
}

When I run the program (in eclipse oxygen 2), it results in the following error

Exception in thread "main" java.lang.NullPointerException 
at javax.swing.ImageIcon.<init>(Unknown Source)
at RegionalResource.<init>(RegionalResource.java:11) 
at RR.main(RR.java:6)
Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
Jashan
  • 47
  • 4
  • 1
    "even when 0th index has a value" It does, but it doesn't correctly point to a resource, so `getClass().getResource(imagenames[0])` is null. – Andy Turner Apr 23 '18 at 12:38
  • Can you share where you have put `1.png` and `2.png`? – Impulse The Fox Apr 23 '18 at 12:40
  • @ImpulseTheFox In workspace/RegionalResource/src – Jashan Apr 23 '18 at 12:43
  • 1
    Okay, so the array should either look like `{"/1.png", "/2.png"}` or the call should look like `getClass().getClassloader().getResource(imagenames[0])` (notice the added `getClassloader()`). This will get resources from the classpath root. – Impulse The Fox Apr 23 '18 at 12:47
  • @ImpulseTheFox For some reason, the program worked when I put the image files inside _workspave/RegionalResource/bin_ Also, sorry if that's nitpicky, but getClass**L**oader is the correct terminology :) – Jashan Apr 23 '18 at 12:54
  • Yup, that was my bad. – Impulse The Fox Apr 23 '18 at 12:56

0 Answers0