Java(GUI)多次添加JButton?

标签 java swing user-interface jbutton

我正在学习 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/

相关文章:

user-interface - 如何在 flutter 中对齐TabBar的元素?

c++ - 基于配置文件的通用 GUI

c - 是否有任何以 C DLL 形式存在的 GUI 工具包?

Java,带有索引空格的格式字符串

java - 为什么这个 Spring AOP 切入点没有被触发?

Java Paint 组件不工作

java - 如何更改 JButton 的图像?

java - 如何在 java 中压缩或解压缩时向 zip 实用程序添加进度条?

java - 在 SQLite 数据库中存储数组的 ArrayList

java - 从 TortoiseSVN 自动结帐