我正在尝试创建一个生成10张扑克牌的java程序。扑克牌采用gif格式。我试图将它们放在一个数组中,但不知道我是如何进行的。理想情况下,应该在没有严格放置的情况下显示扑克牌。无论如何都会留下这些卡片。需要提示才能获得成功。就目前而言,我没有收到任何错误消息。但是出现的盒子是空的。我该怎么办?
提前致谢
cards.java
public abstract class cards extends JPanel {
Random gen = new Random();
int noOfCards = 10;
int line;
int col;
boolean faceUp;
String back = "img/b2fv.gif";
JLabel[] stackLabel = new JLabel[noOfCards];
ImageIcon[] stack = new ImageIcon[noOfCards];
ImageIcon [][] cards = {
{new ImageIcon("img/c1.gif"), new ImageIcon("img/d1.gif"), new ImageIcon("img/h1.gif") , new ImageIcon("img/s1.gif")},
{new ImageIcon("img/c2.gif"), new ImageIcon("img/d2.gif"), new ImageIcon("img/h2.gif") , new ImageIcon("img/s2.gif")},
{new ImageIcon("img/c3.gif"), new ImageIcon("img/d3.gif"), new ImageIcon("img/h3.gif") , new ImageIcon("img/s3.gif")},
{new ImageIcon("img/c4.gif"), new ImageIcon("img/d4.gif"), new ImageIcon("img/h4.gif") , new ImageIcon("img/s4.gif")},
{new ImageIcon("img/c5.gif"), new ImageIcon("img/d5.gif"), new ImageIcon("img/h5.gif") , new ImageIcon("img/s5.gif")},
{new ImageIcon("img/c6.gif"), new ImageIcon("img/d6.gif"), new ImageIcon("img/h6.gif") , new ImageIcon("img/s6.gif")},
{new ImageIcon("img/c7.gif"), new ImageIcon("img/d7.gif"), new ImageIcon("img/h7.gif") , new ImageIcon("img/s7.gif")},
{new ImageIcon("img/c8.gif"), new ImageIcon("img/d8.gif"), new ImageIcon("img/h8.gif") , new ImageIcon("img/s8.gif")},
{new ImageIcon("img/c9.gif"), new ImageIcon("img/d9.gif"), new ImageIcon("img/h9.gif") , new ImageIcon("img/s9.gif")},
{new ImageIcon("img/c10.gif"), new ImageIcon("img/d10.gif"), new ImageIcon("img/h10.gif") , new ImageIcon("img/s10.gif")},
{new ImageIcon("img/cj.gif"), new ImageIcon("img/dj.gif"), new ImageIcon("img/hj.gif") , new ImageIcon("img/sj.gif")},
{new ImageIcon("img/cq.gif"), new ImageIcon("img/dq.gif"), new ImageIcon("img/hq.gif") , new ImageIcon("img/sq.gif")},
{new ImageIcon("img/ck.gif"), new ImageIcon("img/dk.gif"), new ImageIcon("img/hk.gif") , new ImageIcon("img/sk.gif")},
{new ImageIcon("img/jr.gif"), new ImageIcon("img/jb.gif")}
};
public JLabel[] genCards(){
try{
for(int i = 0; i < noOfCards; i++){
line = gen.nextInt(14);
col = gen.nextInt(4);
faceUp = gen.nextBoolean();
stack[i] = cards[line][col];
stackLabel[i] = new JLabel();
ImageIcon img;
stackLabel[i].setIcon(img = stack[i]);
this.add(stackLabel[i]);
}
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
System.out.println("Problem med array");
}
return stackLabel;
}
}
table.java
public class table extends cards {
public void paintComponent(Graphics g){
super.paintComponent(g);
for(int i = 0; i < this.stackLabel.length; i++){
//System.out.println(stack[i]);
}
}
答案 0 :(得分:1)
ImageIcon是一个Swing组件,所以只需将这些ImageIcons添加到像JPanel这样的容器中(也许卡片扩展了你的JPanel)。容器本身会绘制它包含的Swing组件,因此您不必手动绘制它们。
答案 1 :(得分:1)
至少你必须在某个地方打电话给genCards()。可能在构造函数或init方法中:
public Cards(){
genCards();
}