Reputation: 325
I am developing a whack-a-mole game in java. I am creating a 10*10 grid of buttons. However I am not being able to access the id of the clicked button in the actionlistener. Here is the code I have so far.
String buttonID;
buttonPanel.setLayout(new GridLayout(10,10));
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
buttonID = Integer.toString(++buttonCount);
buttons[i][j] = new JButton();
buttons[i][j].setName(buttonID);
buttons[i][j].addActionListener(this);
buttons[i][j].setDisabledIcon(null);
buttonPanel.add(buttons[i][j]);
}
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource()==startButton) {
System.out.println("Game has been started");
}
if (ae.getSource() == "34") { //please see the description below
System.out.println("Yes I have clicked this button");
}
else {
System.out.println("Other button is clicked");
}
}
Currently I have just printed a few things. I don't know how to compare the ae.getsource() with the button that was clicked. I just tried trying to compare it with "34". But when I click the 34th button on the grid it still prints "Other button is clicked".
Upvotes: 3
Views: 2413
Reputation: 347184
Use the buttons actionCommand
property to uniquely identify each button as per your requirements...
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
buttonID = Integer.toString(++buttonCount);
//...
buttons[i][j].setActionCommand(String.toString(buttonID));
//...
}
}
Then in you actionPerformed
method, simple look up the actionCommand
property of the ActionEvent
....
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
if ("0".equals(cmd)) {
//...
} else if ...
Equally, you could using your buttons
array to find the button based on the ActionEvent
's source
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (source == (buttons[i][j])) {
//...
break;
}
}
}
But that's up to you...
Upvotes: 4
Reputation: 10220
Use the button object, instead of the string. You don't need to keep track of the id or name of the button. Simply loop through all the buttons to figure out the source.
You can push all the whack-a-mole buttons in a list, when creating the buttons. And iterate through them, when finding the source.
Use setActionCommand()
& getActionCommand()
instead of setName()
to process the button whacked.
for(JButton button : buttonList )
if (ae.getSource() == button) {
//Do required tasks.
}
Upvotes: 1