2011-10-04 84 views
0

我正在学习Java和我创建一个内存类型的游戏,你必须找到两个平等的卡片。Java(GUI)多次添加JButton?

我创建了一个窗口等等等,但我的问题是添加多个JButtons它。 (我的卡片是带图标的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]); 
    } 

回答

4

你的代码最终添加每个Kort物体到容器两次,由于阵列temp包含两个引用到每个Kort。当您第二次添加Kort时,它会移至第二个位置。 A Component一次只能出现在一个地方。

+0

我不太清楚,我明白了。由于k []包含我所有的卡,我想创建一个新的数组temp,我从K/2填充temp/2。然后另一半温度(温度/ 2)将包含相同的一组卡。即temp/2的副本。所以这不会工作,或者我只是写我的代码错了? – TutenStain

+2

你的循环完成你所描述的内容,所以在这个意义上它是“正确的”。但是,您不能两次将卡片添加到容器中,并期望在容器中获得两张卡片,而不是两次进入您的汽车,并期望成为您自己的乘客:)如果您需要两张相同的卡片出现在容器在同一时间,你必须创建两个独立但相同的'Kort'对象来表示它们。 –

+1

很好的解释!得到它的工作。谢谢! – TutenStain

0

您必须创建sum JButton对象不是sum/2;否则2个按钮是相同的,因此只显示一次。

2

您不得添加两次相同的窗口小部件。你需要两个单独的按钮(但你可以在两个上使用相同的图标)。