eclipse java - 如何使用for语句在java中的数组中创建多个图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14305100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create multiple images in an array in java using a for statement?
提问by Hayden Holligan
I wish to link to the 52 card images to an array, but without adding them individually. I was thinking something like creating an array and using a piece of code something like this.
我希望将 52 张卡片图像链接到一个数组,但不单独添加它们。我正在考虑创建一个数组并使用类似这样的一段代码。
Image[] card;
card = new int[52];
for (int c = 1; c<=52;c++)
{
card[c] =
}
I'm not sure how to proceed, but the cards in the file are labelled 1-52 so I figured that would be an easier way(and a better way to impress my teacher) to create the card values. I thnk I might also have to change the ranks system and use that as well. I'm using slick2d for the graphics.
我不确定如何进行,但文件中的卡片被标记为 1-52,所以我认为这将是一种更简单的方法(也是给我的老师留下深刻印象的更好方法)来创建卡片值。我想我可能还需要更改排名系统并使用它。我正在使用 slick2d 作为图形。
How can I use that piece of code(or a different piece of code) to assign the images to a variable?
如何使用那段代码(或另一段代码)将图像分配给变量?
回答by Samantha Connelly
Check out slick2d javadoc at http://www.slick2d.org/javadoc/and find the Image class you are trying to use.
在http://www.slick2d.org/javadoc/查看 slick2d javadoc并找到您尝试使用的 Image 类。
Try this code
试试这个代码
Image[] card = new Image[52];
for (int i = 0; i < 52; i++)
{
card[i] = new Image(/*insert constructors here*/);
}
If you read the documentation you will find out there are many different ways to create a new image object. e.g. I downloaded an ace of spades image and the following code should create an array of 52 aces of spades
如果您阅读文档,您会发现有许多不同的方法可以创建新的图像对象。例如,我下载了一张黑桃 A 图像,下面的代码应该创建一个包含 52 张黑桃 A 的数组
Image[] card = new Image[52];
String fileLocation = "C:\Users\con25m\Pictures\ace_spades.jpg";
for (int i = 0; i < 52; i++)
{
card[i] = new Image(fileLocation);
}
You can either find out if slick2d has images for all of the cards in a standard 52 deck or download images of each card yourself, come up with a naming convention for the images and then update the fileLocation string in the forloop. e.g.
您可以找出 slick2d 是否有标准 52 副牌中所有卡片的图像,或者自己下载每张卡片的图像,为图像提出一个命名约定,然后更新 forloop 中的 fileLocation 字符串。例如
Image[] card = new Image[52];
String fileLocation = new String();
for (int i = 0; i < 52; i++)
{
fileLocation = "C:\Users\con25m\Pictures\" + i + ".jpg";
card[i] = new Image(fileLocation);
}
Note: instead of using the number 52 all of the time consider using a final variable and using that variable instead. e.g.
注意:不要一直使用数字 52,而是考虑使用最终变量并使用该变量。例如
final int NUMBER_OF_CARDS = 52;
Image[] card = new Image[NUMBER_OF_CARDS];
for (int i = 0; i < NUMBER_OF_CARDS; i++)...

