I did make some attempts to search for this problem but was not sure exactly what to search for and being after 1AM my eyes wouldn't take reading through the 11+ pages of unrelated search results, so I will just ask the question...
New to Java, want to use one listener for multiple JButtons so I make a class that implements ActionListener.
For testing I want to add a JLabel to a JPanel with the text name I have given the button that triggered the event.
I pass a reference to the JPanel I want to add the JLabel to to the constructor of my new class implementing the ActionListener and assign it to a JPanel variable "j".
In the actionPerformed() method I want to get the name of the JButton which is the source of the event, and put it in a JLabel, and add it to the JPanel, here is my code for the actionPerformed() method:
public void actionPerformed( ActionEvent e ){
JButton t = (JButton)e.getSource();
//t.setText( String.format( "%s!", t.getText() ) );
String name = t.getName();
j.add( new JLabel( name ) );
}
Here is the part that is either strange, or I am just strange and it is normal.
The code the way you see it, with that line that alters the text of the JButton commented out, DOES NOT WORK.
If I uncomment that line and alter the text property of the JButton, then everything works fine except that I have altered the Text of the JButton triggering the event.
I have tried so many ways to write this method and it did not matter what or how, I HAD TO CHANGE A PROPERTY OF THE JBUTTON in order for the JLabel to be added to the the JPanel(j).
I even tried to set the name without changing it, ie.
t.setText( t.getText() ); // and many variations of the same thing
Don't work, I actually have to make a real change of one of JButton's properties for the rest of the code to work.
Again, I am new to Java, perhaps I am going about this the wrong way, maybe I am on target, either way I am stumped trying to understand this behavior, even if changing a property didn't affect the application, doing so just to get it to work would really bother me that I had to hack it to make it work.