[英]How do I add images to an image array?
我正在制作一個顯示基於10個隨機整數的10張卡片的隨機集合的applet。
我的想法是制作一個由52個可顯示卡組成的數組(不包括小丑),並基於像這樣的隨機整數顯示數組中的每個卡(對不起,我不知道如何使用代碼塊):
for (int i = 0; i<cards.length; i++) { //cards being my image array
//code that displays each image
}
但是我在嘗試將圖像添加到陣列時遇到麻煩,我也不知道如何顯示陣列中的圖像。
我應該這樣添加它們嗎:
Image[] cards = new Image[52];
cards[0] = c1; //name of the Ace of Clubs, I had used getImage() to already get it
前面的語句拋出錯誤,指出這是一個非法的開始。
合並圖像后,我也需要顯示圖像的幫助,因為我不認為:
System.out.println(cards[x]);
將與圖像一起使用。
在此先感謝您,感謝您看起來如此復雜,我已經盡力減少了!
所以,這是我的愚蠢做法...
public class RandomCards {
public static void main(String[] args) {
new RandomCards();
}
public RandomCards() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new RandomCardsPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception exp) {
exp.printStackTrace();
}
}
});
}
public class RandomCardsPane extends JPanel {
// A list is a collection of Image objects...
private List<Image> cardList;
private Image card = null;
public RandomCardsPane() throws IOException {
// My cards are stored in the default execution location of the program
// and are named "Card_1.png" through "Card_51.png"...
// You image loading process will be different, replace it here..
// ArrayList is a dynamic list (meaning it can grow and shrink
// over the life time of the list) and is backed by an array
// which shouldn't concern you, the only thing you really need to
// know is that it has excellent random access...
cardList = new ArrayList<Image>(51);
for (int index = 0; index < 51; index++) {
cardList.add(ImageIO.read(new File("Card_" + index + ".png")));
}
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
card = cardList.get(Math.min((int)Math.round(Math.random() * cardList.size()), 51));
repaint();
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (card != null) {
int x = (getWidth() - card.getWidth(this)) / 2;
int y = (getHeight() - card.getHeight(this)) / 2;
g.drawImage(card, x, y, this);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(225, 315);
}
}
}
我還寧願使用ImageIO
不是Toolkit.getImage
甚至ImageIcon
,除了它保證在方法返回之前加載圖像數據外,它還支持更多圖像格式,並且可以通過插件擴展...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.