java - 如何将图片放到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)
{
}
解决方案
我不确定将对象设为图像是什么意思...我没有看到任何带有苹果定义的代码...
您是否尝试过使用纹理?您可以轻松地创建一个包含不同纹理的 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();
推荐阅读
- javascript - 如果文本为 NA,则删除动态加载的工具提示表 tr
- docker - Nginx 到 Docker 容器的动态代理
- html - 根据页面更改角材质导航栏上的按钮
- kubernetes - 访问运行在 Kubernetes 集群上的应用程序
- angular - 角模块结构
- flutter - 如何从 VS 代码中隐藏自动生成的文件
- python - python函数中r[( s== 'even'::2) 的含义
- c# - 为什么 MeasureString 会抛出读/写内存错误?
- visual-c++ - 未解析的外部符号 _IID_IDXGIAdapter4
- node.js - WebRTC:Digitalocean 服务器上未显示音频