1

I'm just starting to get used to listeners but I am still kind of new to working with them. I need to reference a button inside of its actionlistener to get the text of that button. my code I want is:

for(int i = 0; i<48; ++i){
        button[i] = new JButton("");
        contentPane.add(button[i]);
        button[i].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                x_marks_the_spot();
                if(button[i].getText().equals("X")){
                    increase_hit();
                }
                else{
                    increase_miss();
                }
            }
        });

Obviously I can't do this because [i] doesn't actually exist in the anon portion of code. I am sure there is a way to do this by getting the source, but I can't think of it.

2 Answers2

3

do this by getting the source

I believe what you want is ActionEvent.getSource()

vandale
  • 3,600
  • 3
  • 22
  • 39
0

Obviously I can't do this because [i] doesn't actually exist in the anon portion of code.

You could do it by copying i into a final variable:

// Make a final copy of loop variable before making the listener
final tmpI = i;
...
// Use your final variable instead of `i` inside the listener
if(button[tmpI].getText().equals("X")){

However, this is not the most efficient way of doing it, because each button would need its own listener object, with the reference to tmpI stored inside the code.

You can create a single ActionListener object, and share it among all buttons, like this:

ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        x_marks_the_spot();
        JButton sender = (JButton)e.getSource();
        if(sender.getText().equals("X")){
            increase_hit();
        } else{
            increase_miss();
        }
    }
};
for(int i = 0; i<48; ++i){
    button[i] = new JButton("");
    contentPane.add(button[i]);
    button[i].addActionListener(listener);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • thank you, I didn't use this code exactly, but I needed to see how the source was actually called and then translated to button that could be referenced. –  Jun 19 '15 at 02:04