phcoding
phcoding

Reputation: 608

Adding ActionListeners to an array of buttons in an applet

I have made a game where a user must input a binary number equivalent to a decimal. User clicks on buttons that toggle between 0 and 1. This worked fine as an application in eclipse but when I tried to run as an applet it did not run correctly. Only the first button registered any events( only the first action listener was added?) How can I get this to work? Any helpful suggestions welcomed!

for(int i = 0; i < buttons.length; i++) {
    buttons[i] = new JButton("0");
    buttons[i].setActionCommand("0");
    buttons[i].setEnabled(true);
    bpanel.add(buttons[i]);
}                                 

    for (int i = 0; i<size;){
    buttons[i].addActionListener(   
    new ActionListener(){
           public void actionPerformed(ActionEvent e) {
           String choice = (String) e.getActionCommand();        

Upvotes: 2

Views: 668

Answers (2)

exexzian
exexzian

Reputation: 7890

You have set same action command on all your buttons:
buttons[i].setActionCommand("0");

and here this particular code:
String choice = (String) e.getActionCommand(); returns 0 for every button click

Try setting different action commands for each button

Upvotes: 1

Dan D.
Dan D.

Reputation: 32391

All your buttons have the same text and the same action command.

You should probably change the first lines in the first loop to something like:

buttons[i] = new JButton(i + "");
buttons[i].setActionCommand(i + "");

Upvotes: 1

Related Questions