I'm developing a GUI program, where I have made classes, that cluster ActionListeners, by functionality. My question is regarding how the JVM handles jButtons, that has the same ActionListener added to them.
First; I am aware that the JVM can save memory, by letting two reference variables that point to an identical string (for instance), point to the same string object in the memory.
public class Example {
String str1 = "SomeString";
String str2 = "SomeString";
}
Now, my question is this: If I have, say, 5 jButtons. All buttons have the same ActionListener added to them. When the program is run, will they have 5 seperate, identical, instaces of the same class added to them? Or will the JVM do something similar (to the above mentioned) ?
Well, it really depends on how you created the ActionListeners
. If you did
button1.addActionListener(new ActionListener() {
....
});
....
button5.addActionListener(new ActionListener() {
....
});
Or
ActionListener al= new ActionListener() {
....
};
button1.addActionListener(al);
....
button5.addActionListener(al);
In the first case you, true, have 5 different action listeners. But in the second you have only one. When can you have only one? When it does exactly the same and on the same objects.
It depends.
This will give them the same instance.
ActionListener al = new ActionListener() { ... };
button.addActionListener(al);
button2.addActionListener(al);
...
while this will give them their own.
button.addActionListener(new ActionListener() { ... });
button2.addActionListener(new ActionListener() { ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With