将图片加载到我的java游戏中的错误 [英] Bug loading a picture into my java game

查看:128
本文介绍了将图片加载到我的java游戏中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在尝试制作一款java游戏并试图上传图片以测试我的调整大小,但是我根本无法加载图片。

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);
}

我的png文件在我的班级所在的包中但是我得到了我尝试使用getResource()的行上的空指针异常。感谢提前感谢任何帮助。

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.

推荐答案

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

我猜您的文件路径中不需要/。

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

此外,自定义绘画是通过覆盖paintComponent()方法而不是paint()方法完成的。

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

编辑:


我应该为paintComponent方法做什么

What should I be doing for the paintComponent method

只需将方法从paint()重命名为paintComponent()。此外,您应该始终调用super.paintComponent(g)作为第一个语句。

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

然而,由于您可以使用JLabel,因此没有理由进行任何自定义绘制用图标显示图像。

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游戏中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆