I have an array of Tile objects (Panel, Button to a tile) in a JPanel, 20x20. If button 1 is clicked, a thing happens, button 2 is pressed, a thing happens, etc.
I want a specific function to happen every time a button other than one in the top row is clicked (the top row of buttons all have functions assigned, the other 380 buttons do not have assigned functions).
So in the top buttons' cases I have the code:
if(e.getSource() == tiles[0][0].button)
{
//do stuff
}
else if(e.getSource() == tiles[0][1].button)
{
//do stuff
}
For the other buttons, I want something along the lines of:
JButton button;
button = e.getSource();
JPanel hostPanel = button.PanelInWhichButtonisContained();
but I'm not sure what the syntax or what sort I would to do achieve that task. I don't really have any code to present prior attempts because I'm not sure how to approach this task, but I haven't been able to find anything on the World Wide Web to help me in this task.
I'm currently just using default application window libraries and classes (javax.swing, java.awt, etc) but I'm completely open to downloading external libraries.
Determining the "source" of an action like a button press in the
actionPerformed
method is usually brittle (and fortunately, hardly ever necessary).This means that this is highly questionable:
You should usually NOT do this.
And of course, it's even worse to add casts and walk up some container hierarchy:
In basically all cases, it is far more flexible and elegant to attach a listener to the button that is specific for the button - meaning that it knows what the button should do.
For individual buttons, this can be solved the old-fashioned way, using an anonymous inner class:
The same can be written far more concisely using lambda expressions with Java 8:
(A side note: I consider it as a good practice to only call a single method in the
ActionListener
implementation anyhow. TheactionPerformed
method should not contain many lines of code, and particularly no "business logic". There should be a dedicated method for what the button does - for example, tostartSomething
, as in the example above)For buttons that are contained in arrays, as in the example in your question, there is a neat trick to retain the information about the button that was clicked:
In many cases, you then don't even have to keep the
JButton buttons[]
array any more. Often you can just create the buttons, add them to some panel, and then are only interested in theindex
that is passed to theclickedButton
method. (Thebutton[]
array may be necessary in some cases, though - for example, if you want to change the label of a button after it was clicked).