开发者

Help with buttonWatcher adding Characters to an 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');
      }

   }
}
}

I am trying to get this code so when one of the button开发者_如何学Pythons 1-4 is clicked it adds A-D to the arrayList playerSequence, and as far as i can see it isnt happening. Have i missed something out?


I think your IF statements are checking for the wrong actionCommand string.
You set the actionCommand of each button to the characters 'A'-'D' but your IF statements check for '1'-'4'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜