1

I just have a question on the following. I've got a 2D array of buttons that require me to run another method when I click on them. My current method relies on the following input, a String (which I can get from the user easily) and two integer values. These are dictated by the buttons position in the array.

I have a button listener attached to these buttons but I am not too sure how I can work out what the button's position actually is. I've made my own button class (because I wanted some specific settings and I thought it would be easier) and when making it I implemented a method called getXPos and getYPos which basically hold the values for the actual button in the array when it was created. Thing is I don't know how to retrieve these values now as the listener doesn't actually know what button is being pressed does it?

I can use the getSource() method but I then don't know how to invoke that source's methods. For example I tried to do the following.

int x = event.getSource().getXPos(); but I am unable to do this. Is there any way of telling what button I have pressed so I can access it's internal methods or something similar? Thanks!

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Scott
  • 465
  • 3
  • 10
  • 22

1 Answers1

2

To call a method on the source, you have to cast it first. If you're never adding your ActionListener to anything but an instance of your special MyButton with its x and y variables, you can do this:

MyButton button = (MyButton) event.getSource();
int x = button.getXPos();
int y = button.getYPos();

Then MyButton contains the x and y:

public class MyButton extends JButton {

    private int xPos;
    private int yPos;

    // ...

    public int getXPos() {
        return xPos;
    }

    public int getYPos() {
        return yPos;
    }
}

And make sure you're always adding your listener to instances of MyButton:

MyButton myButton = new MyButton();
// ...
myButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        MyButton button = (MyButton) e.getSource();
        int xPos = button.getXPos();
        int yPos = button.getYPos();
        // Do something with x and y
    }
});
Brian
  • 17,079
  • 6
  • 43
  • 66
  • Worked perfectly wasn't aware you could also cast objects, only thought it was primitives. Problem solved thank you so much EDIT: To confirm yes I made a special button listener just for these specific buttons, and my method was very similar to above. – Scott Oct 13 '12 at 03:37
  • Indeed, casting applies to everything. Check out [this Java trail on inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html). It covers casting objects in addition to other inheritance properties. – Brian Oct 14 '12 at 00:01
  • brian, in your ActionListener code you say `event.getSource()` do you mean `e.getSource`? – Ungeheuer Jun 08 '15 at 00:03
  • Thanks @Johnny, I've fixed it. – Brian Jun 09 '15 at 14:30