简体   繁体   English

将图像添加到Java小程序?

[英]adding images to a java applet?

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

How do you display an image and where do you put it in an eclipse project? 如何显示图像并将其放在Eclipse项目中的什么位置?

Eclipse IDE executes the programs from the src directory. Eclipse IDE从src目录执行程序。 These steps solved me this problem. 这些步骤解决了我这个问题。

  1. Create a new package called resources . 创建一个名为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. 希望这能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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