java - 获取已添加到 JFrame 中的按钮

标签 java swing

我正在开发一个简单的 15 谜题游戏。我向 JFrame 添加了 16 个生成的编号按钮,这就是练习(大学)。 我现在正尝试进一步进行交互,因此我需要获取所有按钮并将它们放入 2D vector 中,以便计算用户单击的位置以及单元格是否可以“滑动”以及在哪里“滑动”,但我不知道如何从框架中获取它们。

这是生成器代码:

public void generation(){
    int num;
    Random rand = new Random();
    ArrayList<String> list = new ArrayList<String>();

    for(int i = 0; i < this.getTot(); i++)
        list.add(""+ i);

    while(!list.isEmpty()){
        do{                     
            num = rand.nextInt(this.getTot());
        } while (!list.contains("" + num));

        list.remove("" + num);

        if(num == 0){
            this.add(new Button(" ");
        }
        else{
            this.add(new Button("" + num);                  
        }
    }
}

这是构造函数:

public Base15(int x, int y){
    this.setSize(WIDTH, HEIGHT);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    this.setLayout(new GridLayout(x, y));

    this.x = x;
    this.y = y;

    this.generation();
    this.cells = new Button[x][y];  
}

谢谢。

更新:遵循 ufis 建议并完成了二维数组!

for (int row = 0; row < x; row++){
        for (int col = 0; col < y; col++){
            do{                     
                num = rand.nextInt(this.getTot());
            } while (!list.contains("" + num));

            list.remove("" + num);

            if(num == 0){
                cells[row][col] = new Button(" ", sw, label);
                this.add(cells[row][col]);

            }else{
                cells[row][col] = new Button("" + num, sw, label);
                this.add(cells[row][col]);

            }
        }

谢谢大家!

最佳答案

除非我完全误解你的问题,否则你可以这样做

JFrame theFrame = new JFrame();
// lots of code here to add buttons
Component[] components = theFrame.getComponents();
for (Component component : components) {
    if (component instanceof Button) {
        // do something
    }
}

但是,如果您在创建/将所有按钮添加到框架时存储一些对它们的引用,那就更好了。

<小时/> 编辑: 我认为您应该在将按钮添加到框架时检查创建按钮的方式。

当你这样做时

JFrame theFrame = new JFrame();

for (int i = 0; i < 15; i++) {
    theFrame.add(new Button());
}

您没有对您的 Button 的引用。这就是为什么您需要“从框架中获取 Button”。

如果你做了类似的事情

JFrame theFrame = new JFrame();
Button[] buttons = new Button[15];

for (int i = 0; i < 15; i++) {
    buttons[i] = new Button();
    theFrame.add(buttons[i]);
}

您不必在稍后阶段循环遍历所有组件,因为您已经引用了按钮数组中的按钮。当然,您也可以将其设为 Button[][]。但这里的优点是您可以在创建时引用按钮列表。

关于java - 获取已添加到 JFrame 中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21090812/

相关文章:

java - 从 JTextField 获取字符串输入并将该字符串设置为 JLabel

Java ActionListener 不适用于 JMenuItem

java.lang.NoClassDefFoundError : org/apache/poi/ss/usermodel/Row 错误

java - JTable 没有显示在 UI 中?

java - 看似简单的 FNV1 哈希实现导致大量冲突

java - Liferay 使用合金 ui 的日期选择器

java - Spring 3.0.5 + hibernate 3.6 hibernate.show_sql 未显示。是否由于使用了事务?

java - 如何将 java.util.List[java.lang.Long] 转换为 java.util.List[Long]

java - 为什么我在循环中看不到静态变量?

java - 事件处理 Swing 组件