简体   繁体   中英

getClass().getResource() Exception?

I'm trying to learn how to add images to my JFrame. I'm adequate in GUI, but I simply cannot understand why this doesn't work.

I have arrays set so that I can I can do multiple images, in case you wondering.

(1) MY problem is the getClass().getResource("0.png"); for some reason this keeps failing. When the main(S...) goes to create the object GUIv1, it fails in the image[0].....0.png");

No idea why, I'm using eclipse, and the images are right in the default package where my class is at. Any takes?

(2) there seems to be something wrong here also, but it is not the cause of the first exception, I'd appreciate an answer for this one also.

(I do apologize about the code font if its wrong, this is my first time here).

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

public class GUIv1 extends JFrame{

private static int tilesnum = 2;
private static ImageIcon[] image = new ImageIcon[tilesnum + 2];
private static JLabel[] imagepanel = new JLabel[tilesnum + 2];

public GUIv1() {
    setLayout(new FlowLayout());

    image[0] = new ImageIcon(getClass().getResource("0.png"));     //HERE (1)
    image[1] = new ImageIcon(getClass().getResource("1.png"));
    image[2] = new ImageIcon(getClass().getResource("2.png"));
    image[3] = new ImageIcon(getClass().getResource("3.png"));

    for(int i = 0; i < tilesnum + 2; i++) {
        imagepanel[i] = new JLabel(image[i]);
        add(image[i]);                                         //HERE (2)
    }

}

public static void main(String[] args) {

    GUIv1 selectorframe = new GUIv1();  
    selectorframe.setTitle("MapEditor v2");
    //JFrame mainframe = new JFrame("MapEditor v2");    
    selectorframe.pack();
    selectorframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    selectorframe.setVisible(true);
}   
}

When using getClass().getResource() , your images must be located in the same location as your class file GUIv1.class , otherwise an NPE will result when the null value is passed into the constructor of ImageIcon .

If you're unsure where the class root is (in this case, where the images should be located), you can display the result of:

System.out.println(getClass().getProtectionDomain().getCodeSource().getLocation());

in your constructor.

Secondly, you cannot add an ImageIcon directly to your JFrame container as it's not a component. You can add your Jlabel , this is a component:

add(imagepanel[i]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM