Reputation:
I have encountered a problem I can't find the solution for, in Java revolving around JButtons.
As I want to keep my code 'cleaner', I have declared all my buttons using the following for
loop:
JButton[] buttons= new JButton[10];
for(int i = 0;i < buttons.length;i++){
buttons[i] = new JButton("Example "+i);
contents2.add(buttons[i]);
buttons[i].addActionListener(listener);}
And the actionListener listener
is as follows:
ActionListener listener = new ActionListener() {
public void actionPerformed (ActionEvent actionEvent) {
if(actionEvent.getSource() == (JButton)buttons[1].getSource()){
System.out.println("Test");
}
}
};
However then buttons
in if(actionEvent.getSource() == (JButton)buttons[1].getSource())
has Eclipse tell me Buttons cannot be resolved to a variable.
In that same line, I've also tried without the (JButton)
, without the .getSource()
after buttons[1]
, and more combinations.
I have confused myself, however I simply want the action performed in the listener
to happen if the button pressed was _.
Sorry for the confusion, but if you understand this, any help would be appreciated. I just keep getting strings other than what I desire.
Upvotes: 0
Views: 59
Reputation: 26198
Instead of using source which does not exist, you can use the setActionCommand
method to be used in your action listener.
sample:
ActionListener listener = new ActionListener() {
public void actionPerformed (ActionEvent actionEvent) {
String index = actionEvent.getActionCommand();
switch(Integer.valueOf(index)){
case 1: //your actions here for index 1 of button
break;
}
}
};
final JButton[] buttons= new JButton[10];
for(int i = 0;i < buttons.length;i++){
buttons[i] = new JButton("Example "+i);
contents2.add(buttons[i]);
buttons[i].setActionCommand(i+"");
buttons[i].addActionListener(listener);
}
As you could see the action command
is the index of your button so you could use the switch statement for performing actions on each of your buttons.
case 1
means the index 1
of your Button
array.
Upvotes: 1
Reputation: 347294
It's possible that the ActionListener
is been declared before the JButton
array.
Instead, declare buttons
as a instance variable...
public class SomeClass extends ... {
private JButton[] buttons;
Then you should be able to reference buttons
in your ActionListener
using
if(actionEvent.getSource() == buttons[1]){
When constructing your buttons array, you will also need to make sure you are not shadowing your variables, for example...
buttons= new JButton[10];
for(int i = 0;i < buttons.length;i++){
Having said all that, if you want to clean up your code, then I would suggest you take a look at How to use Actions, which provides a re-usable API for actions, which can be attached to buttons, menu items and key bindings
Upvotes: 1