Bug loading a picture into my java game

2019-09-21 19:59发布

问题:

Hello I'm trying to make a java game and am trying to upload a picture to test my resizing, however I am unable to load the picture in at all.

ImageIcon img1 = new ImageIcon(this.getClass().getResource("/Pic.png"));
Image im1 = img1.getImage();

public void paint(Graphics g)
{
    Graphics2D g2d = (Graphics2D) g; 
    g2d.drawImage(im1, 0, 0, null);
}

I have my png file inside the package that my class is in but I get a null pointer exception on the line where I try to use getResource(). Any help is appreciated thanks in advance.

回答1:

ImageIcon img1 = new ImageIcon(this.getClass().getResource("/Pic.png"));

I would guess you don't need the "/" in your file path.

Also, custom painting is done by overriding the paintComponent() method NOT the paint() method.

Edit:

What should I be doing for the paintComponent method

Just rename the method from paint() to paintComponent(). Also, you should always invoke super.paintComponent(g) as the first statement.

However, there is really no reason to do any custom painting because you can use a JLabel with an Icon to display an image.



标签: java image load