首页 > 解决方案 > 如何将图片放到Java中的对象上?

问题描述

好吧,我尝试让一个对象成为一个图像,一个进入 ArrayList 的对象。但我不知道该怎么做。我尝试了几种方法,但我尝试过的方法都没有奏效。你认为应该添加什么?我的对象叫做Apple.Thanks提前


    public class Gamepanel extends JPanel {

     public void tick()
    {
         if(apples.size()==0)
        {
            //System.out.println(apples.size());
            int xC=r.nextInt(79);

            int yC=r.nextInt(79);

            apple=new Apple(xC,yC,10);
            apples.add(apple);
        }
        for(int i=0;i<apples.size();i++)
        {
            if(xC==apples.get(i).getxC()&&yC==apples.get(i).getyC())
            {   
                size++;
                score++;
                apples.remove(i);
                i++;

            }
        }
    }
    public void paint(Graphics g)
    {   

        //here I draw the snake and his food    
        if(State==STATE.GAME)
        {
            g.clearRect(0, 0, WIDTH, HEIGHT);
            g.setColor(Color.BLACK);
            g.fillRect(0,0,WIDTH,HEIGHT);
        //here i make my map of the game 

        for(int i=0;i<apples.size();++i)
        {
            apples.get(i).draw(g);
        }


}   

公开课 Apple {

private int xC,yC,width,height;

BufferedImage ap=null;

public Apple(int xC,int yC,int titleSize) {

    this.xC=xC;
    this.yC=yC;
    width=titleSize;
    height=titleSize;   
}
//here i want to draw a picture for each my objects from ArrayList
public void draw(Graphics g) 
{

}

标签: javaarraylist2d-games

解决方案


我不确定将对象设为图像是什么意思...我没有看到任何带有苹果定义的代码...

您是否尝试过使用纹理?您可以轻松地创建一个包含不同纹理的 Texture[] 数组以供使用。

Texture[] apples = new Texture[2];

apples[0] = new Texture("apple1.png");
apples[1] = new Texture("apple2.png");

ArrayLists 也可以使用,但我对 2d 游戏的经验是使用 libGDx(我猜你的包是 graphics2D?使用 GDx 你可以......

SpriteBatch batch = new SpriteBatch();

ArrayList<Texture> apples = new ArrayList<Texture>();

//add your textures, then draw using a SpriteBatch

batch.begin();
batch.draw([texture],xpos,ypos); batch.draw(apples.get(i), 150, 500);
batch.end();

推荐阅读