如何在Java中将图片放置到对象上?

好吧,我尝试将一个对象变成一个图像,一个进入ArrayList的对象。但是我不知道该怎么做。我尝试了几种方法,但我尝试过的所有方法均无效。您认为应该添加什么?我的对象叫苹果。谢谢!


    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,WIDTH,HEIGHT);
            g.setColor(Color.BLACK);
            g.fillRect(0,HEIGHT);
        //here i make my map of the game 

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


}   

公共类苹果{

private int xC,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) 
{

}

kyj09 回答:如何在Java中将图片放置到对象上?

我不确定通过使对象成为图像来表示什么意思...我看不到苹果定义的任何代码...

您是否尝试过使用纹理?您可以轻松创建一个包含不同纹理的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();
本文链接:https://www.f2er.com/3157377.html

大家都在问