简体   繁体   English

如何为10 x 10网格按钮布局中的每个JButton提供唯一的ID /名称

[英]How to give each JButton in a 10 x 10 grid button layout a unique ID/name

I am trying to give each JButton from a 10 x 10 button layout (so 100 buttons) each unique name or ID or number so I can call them later. 我试图为每个JButton提供10 x 10的按钮布局(即100个按钮),每个名称,ID或编号都是唯一的,以便以后可以调用它们。 I made an ArrayList because that's what some other person did. 我做了一个ArrayList,因为那是其他人所做的。

public ArrayList<JButton> myList;

//Some other code

        for(int row = 0; row < 10; row++)
        {
            for(int col = 0; col < 10; col++)
            {
                    button = new JButton();
                    button.addActionListener( al );
                    myList.add(button);
                    for(JButton button : myList)
                        button.setText("");
                    panel_1.add(button);
            }
        }

The program compiles but it doesn't run. 该程序可以编译,但是不会运行。 It's showing error at 它在显示错误

myList.add(button);

It's a null pointer exception apparently. 显然,这是一个空指针异常。

but I don't know why. 但我不知道为什么。 Is it not adding the buttons to the ArrayList? 是否没有将按钮添加到ArrayList? Also how do I give each button a unique name or string? 另外,如何为每个按钮赋予唯一的名称或字符串?

The program compiles but it doesn't run. 该程序可以编译,但是不会运行。 It's showing error at 它在显示错误

The ArrayList is null because you didn't create an ArrayList object. ArrayList为空,因为您没有创建ArrayList对象。

The code should be: 代码应为:

private ArrayList<JButton> myList = new ArrayList<JButton>();

Also how do I give each button a unique name or string? 另外,如何为每个按钮赋予唯一的名称或字符串?

There is no need to give the button a unique name. 无需为按钮指定唯一的名称。 Its unique name is the "index" used to access the JButton in the ArrayList . 它的唯一名称是用于访问ArrayListJButton的“索引”。

You probably don't even need the ArrayList. 您甚至可能不需要ArrayList。

Normally you add an ActionListener to the button. 通常,您将ActionListener添加到按钮。 Then you can just use the getSource() method of the ActionEvent to get the reference to the button. 然后,您可以只使用ActionEventgetSource()方法来获取对按钮的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM