【问题标题】:Java (GUI) adding JButton multiple times?Java(GUI)多次添加JButton?
【发布时间】:2011-10-05 01:19:45
【问题描述】:

我正在学习 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]);
    }

【问题讨论】:

    标签: java swing user-interface jbutton


    【解决方案1】:

    您的代码最终将每个Kort 对象添加到容器中两次,因为数组temp 包含对每个Kort 的两个引用。当您第二次添加Kort 时,它会移动到第二个位置。 Component 一次只能出现在一个地方。

    【讨论】:

    • 我不太确定我明白了。由于 k[] 包含我所有的卡片,我想创建一个新数组 temp,我用 K/2 填充 temp/2。然后另一半 temp (temp/2) 将包含同一组卡片。即 temp/2 的副本。所以这行不通还是我只是写错了代码?
    • 您的循环执行您所描述的操作,因此在这个意义上它是“正确的”。但是您不能两次将卡片添加到容器中并期望在容器中获得两张卡片,就像您可以两次进入汽车并期望成为您自己的乘客一样:) 如果您需要两张相同的卡片出现在同时容器,你必须创建两个独立但相同的Kort对象来表示它们。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-07
        • 2012-03-23
        • 1970-01-01
        • 2012-11-02
        • 2020-03-09
        • 2013-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多