private JButton[] buttons;
    private static final Character firstChar = 'A';
    private static final Character lastChar = 'D';
    /** Creates a new instance of ButtonPanel */
    public ButtonPanel()
        buttons = new JButton[4];
        setLayout(new GridLayout(2,2)); 
        Character label = firstChar;
        for (JButton b: buttons)
            b = new JButton("" + label);
            buttons[label - firstChar]= b;
            b.setActionCommand("" + label); // for use in ButtonWatcher
            //is this how to create and add a ButtonWatcher for each of the buttons
            b.addActionListener(new ButtonWatcher());


Ive tried this code with a buttonWatcher implements ActionListener class but it wont work and im wondering have i added the actionListener to each button correctly or is there something else i have to do?

7 Years
Discussion Span
Last Post by jon.kiparsky

What do you mean by "it won't work"? What is it doing or not doing, and what do you expect instead? Is it compiling? Does it run? What happens when it runs, assuming it does?

If it compiles, then that would mean that ButtonWatcher is implementing ActionListener correctly. That only means that it has the required methods, it says nothing about whether they are written so they'll do what you want them to.
This means that a click on one of your buttons will send an ActionEvent to one of your four ButtonWatchers (since you're making a new one for each button), and that this ActionEvent will have an ActionCommand which will be the same as the button's label. Beyond that, there's not much to say from this piece of code.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.