You are loosing references as you go along. In the forst loop you allocate
9 buttons, add them to the container and hook them up to the listener,
ok so far, - but the only button you have a reference to when you exit that
loop is the last button allocated inside the loop
What happends in the next loop is that you are repeatedly setting the label
for that last button.
You can do this at least two ways.
1: Use an array of buttons:
Code:
// allocate an array of button references (all will be null pointers initially)
Button [] buttons=new Button[9];
.
.
for (int i = 0; i < 9; i++) {
buttons[i] = new Button();
this.add(buttons[i]);
buttons[i].addActionListener(this);
}
for (int i = 0; i < arraylist.size(); i++) {
Integer bNo = (Integer) arraylist.get(i);
buttons[i].setLabel(bNo.toString());
}
The plus of the code above is that you will have direct access to all the
buttons after they are made, but its not good code...
2: Do it all in one loop:
Code:
// either this way, using a button array:
Button [] buttons=new JButton[arraylist.size()];
.
.
for (int i = 0; i < arraylist.size(); i++) {
buttons[i] = new Button();
Integer bNo = (Integer) arraylist.get(i);
buttons[i].setLabel(bNo.toString());
this.add(buttons[i]);
buttons[i].addActionListener(this);
}
// or this way, no button array:
for (int i = 0; i < arraylist.size(); i++) {
Button button = new Button();
Integer bNo = (Integer) arraylist.get(i);
button.setLabel(bNo.toString());
this.add(button);
button.addActionListener(this);
}
Bookmarks