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!
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
}
});