开发者

Java (GUI) adding JButton multiple times?

开发者 https://www.devze.com 2023-04-10 21:30 出处:网络
Im learning Java and Im creating a memory type game where yo开发者_开发问答u have to find two equal cards.

Im learning Java and Im creating a memory type game where yo开发者_开发问答u have to find two equal cards.

I have created a Window etc etc but my problem is adding multiple JButtons to it. (my cards are JButtons with icons). I have commented my code where my problem is.

//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]);
    }


Your code ends up adding each Kort object to the container twice, since the array temp contains two references to each Kort. When you add a Kort a second time, it moves to the second location. A Component can only appear in one place at a time.


You may not add the same widget twice. You need two separate buttons (but you may use the same icon on both).


You have to create sum JButton objects not sum/2; otherwise 2 buttons are the same and therefore only displayed once.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号