将图像添加到Java小程序? [英] adding images to a java applet?

查看:33
本文介绍了将图像添加到Java小程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试创建图像时,我正在使用此行,但没有图像,只有空白行.

When I tried to to create an image I was using this line but got no images, just blank lines.

g.drawImage(getImage(getDocumentBase(), "Piece_1.png"),coorx, 
coory, SIZE_Y / 8, SIZE_Y / 8, this);

如何显示图像并将其放置在Eclipse项目中?

How do you display an image and where do you put it in an eclipse project?

推荐答案

Eclipse IDE从 src 目录执行程序.这些步骤解决了这个问题.

Eclipse IDE executes the programs from the src directory. These steps solved me this problem.

  1. 创建一个名为 resources 的新程序包.您可以随意命名.
  2. 将图像文件添加到该程序包中.
  3. 现在在绘制图像之前先加载图像.

  1. Create a new package called resources. You can name it whatever you want.
  2. Add your image files into that package.
  3. Now first load your image before drawing it.

public Image getImage(String name){
    URL imgUrl = getClass().getClassLoader().getResource("resources/"+name);
    ImageIcon icon = new ImageIcon(imgUrl);
    return icon.getImage();
}

一个例子

您可以拥有的构造函数.

An Example

The constructor you can have.

Image piece1;

public Checkers(){
    piece1 = getImage("Piece_1.png");
}

public void paint(Graphics g){
    if (piece1!=null){
        g.drawImage(piece1, xcoord, ycoord, null);
    }
}

希望这可以解决您的问题.

Hope this solves your problem.

这篇关于将图像添加到Java小程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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