One way to handle an array of Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* One way to handle an array of buttons */
public class Buttons extends Applet implements ActionListener
{
//applet member data
Button[] buttonArray;
int nRows = 3;
int nColumns = 4;
int nTotalButtons = nRows * nColumns;
public void init()
{
//declare a grid layout with no space between buttons
setLayout(new GridLayout(nRows, nColumns, 0, 0));
//declare a new array of buttons
buttonArray = new Button[nTotalButtons];
//initialize each of the buttons in the array
//with an empty label
for (int nNum = 0; nNum < nTotalButtons; nNum++)
{
buttonArray[nNum] = new Button("");
add(buttonArray[nNum]);
buttonArray[nNum].addActionListener(this);
buttonArray[nNum].setBackground(Color.yellow);
//each button will send a message with its number
buttonArray[nNum].setActionCommand("" + nNum);
}
}
public void actionPerformed(ActionEvent e)
{
//get the number of the button from getActionCommand
//convert it to an int and store it in nButtonNumber
int nButtonNumber = Integer.parseInt(e.getActionCommand());
//display button Number at bottom of screen
showStatus("Button number " + nButtonNumber);
//change background of buttons
if(buttonArray[nButtonNumber].getBackground() != Color.red)
buttonArray[nButtonNumber].setBackground(Color.red);
else
buttonArray[nButtonNumber].setBackground(Color.blue);
}
}