帮助buttonWatcher将字符添加到arrayList

时间:2011-01-12 00:23:24

标签: java arraylist

public class ButtonPanel extends JPanel
{
    private JButton[] buttons;
    private ArrayList<Character> playerSequence; 
    private static final Character firstChar = 'A';
    private static final Character lastChar = 'D';
    /** Creates a new instance of ButtonPanel */
    public ButtonPanel()
    {
        buttons = new JButton[4];
        playerSequence = new ArrayList<Character>();
        setLayout(new GridLayout(2,2)); 
        Character label = firstChar;
        for (JButton b: buttons)
        {
            b = new JButton("" + label);
            buttons[label - firstChar]= b;
            b.setActionCommand("" + label);
            label++;
            add(b);
            //adds an action listener to all 4 buttons
            b.addActionListener(new ButtonWatcher());  
        }

        setButtonsEnabled(true);
    }


public class ButtonWatcher implements ActionListener
{
   public void actionPerformed(ActionEvent b)
   {
      Object clicked = b.getActionCommand();
      if(clicked.equals("1"))
      {
        playerSequence.add('A');
      }
      if(clicked.equals("2"))
      {
          playerSequence.add('B');
      }
      if(clicked.equals("3"))
      {
         playerSequence.add('C');
      }
      if(clicked.equals("4"))
      {
         playerSequence.add('D');
      }

   }
}
}

我正在尝试获取此代码,因此当单击其中一个按钮1-4时,它会将A-D添加到arrayList playerSequence,并且据我所知,它不会发生。我错过了什么吗?

1 个答案:

答案 0 :(得分:3)

我认为您的IF语句正在检查错误的actionCommand字符串 您将每个按钮的actionCommand设置为字符'A' - 'D',但您的IF语句检查'1' - '4'