我正在学习 Java,我正在创建一个内存类型的游戏,你必须找到两张相同的牌。
我创建了一个窗口等,但我的问题是向其中添加多个 JButton。 (我的卡片是带有图标的 JButton)。我已经对我的问题所在的代码进行了评论。
//Get the images.
private File bildmapp = new File("bildmapp");
private File[] bilder = bildmapp.listFiles();
//My own class extending JButton
Kort[] k = new Kort[bilder.length];
for(int i = 0; i < bilder.length; i++){
k[i] = new Kort(new ImageIcon(bilder[i].getPath()));
}
//Later in my code:
int sum = rows * columns;
Kort[] temp = new Kort[sum];
//My function to randomize.
Verktyg.slumpOrdning(k);
//***********************//
//Trying to fill a array from K (which contains all cards) so my temp contains SUM cards and SUM/2 pairs
for(int i = 0; i < sum/2; i++){
temp[i] = k[i];
temp[i+sum/2] = k[i];
}
//Problem is that i only get SUM/2 (half of the cards) cards, not the 16 (8 pairs) i would like to add in this case
//SYNLIGT = VISIBLE.
for(int i = 0; i < sum; i++){
temp[i].setStatus(Kort.Status.SYNLIGT);
j.add(temp[i]);
}
最佳答案
您的代码最终会将每个 Kort
对象添加到容器中两次,因为数组 temp
包含对每个 Kort
的两个引用。当您第二次添加 Kort
时,它会移动到第二个位置。 组件
一次只能出现在一个地方。
关于Java(GUI)多次添加JButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7651555/