Bug loading a picture into my java game

佐手、 提交于 2019-12-13 22:57:43

问题


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.



来源:https://stackoverflow.com/questions/18927596/bug-loading-a-picture-into-my-java-game

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!