如何创建对象然后将该对象添加到ArrayList?

时间:2013-12-07 01:43:08

标签: java arraylist

对于我的Java项目,我正在从存储在数组中的字符串创建按钮:

public class UserInterface implements ActionListener {
ArrayList<CardButton> currButtonList;   // Current list of card buttons used

public void createAndShowGUI(String[] allCards){

//unrelated to question code

//for each String in allCards[]
for(int i=0; i<allCards.length; i++){
    //Assign the button names relative to which card has is being created
    String name = allCards[i];
    CardButton button = new CardButton(name);
    //add the button to the CardPanel
    button.setFaceDown();
    button.setBorderPainted(false);
    int width = button.getWidth();
    int height = button.getHeight();
    button.setSize( new Dimension( width, height ) );
    //button.setPreferredSize(new Dimension(150, 150));
    CardPanel.add(button);
    currButtonList.add(button);
    }
  }
 //rest of creating the Panels, more unrelated to question code

代码符合但是:      线程“main”java.lang.NullPointerException中的异常                            在memory_game.GameFunction。(GameFunction.java:47) 这是我尝试将侦听器分配给数组列表中的每个对象的位置。 假设ArrayList没有正确添加按钮,我是否正确? 如果是这样,为什么?我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:3)

您需要实例化ArrayList<CardButton>。这是错误的(因为它使currButtonList未定义,即为空) -

ArrayList<CardButton> currButtonList;   // Current list of card buttons used

试试这个

// Current list of card buttons used
List<CardButton> currButtonList = new ArrayList<CardButton>();

或者您可以将其添加到UserInterface构造函数中 -

currButtonList = new ArrayList<CardButton>(); // Instantiate the currButtonList.

最后,关于你的主题问题 - 你似乎正是用这些行正确地做到了 -

CardButton button = new CardButton(name); // Create a new CardButton instance.
currButtonList.add(button); // Add it to the list (currButtonList was null, not button)

答案 1 :(得分:1)

您是否曾像

那样实例化ArrayList
ArrayList<CardButton> currButtonList = new ArrayList<CardButton>();

我不相信ArrayList是一种在不实例化的情况下可以工作的内在类型。

答案 2 :(得分:1)

您的arrayList未初始化,默认为NULL。这就是当您尝试将按钮添加到currentButtonList变量时获得空指针异常的原因。

使用空列表初始化数组,如下所示。

ArrayList<CardButton> currButtonList = new ArrayList<CardButton>();    // Current list of card buttons used