This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Is there a way to change the name of this variable (the identifier, not the type)?
Guess that would be great for loops. For example, when I need to add multiple swing component to a container programmatically: e.g. JMenuItems to a JMenu.
I know it's possible to create a loop and add menu items from one variable being created anew for each iteration, but then these menu items will be anonymous, right?
So I guess there are two questions here: 1. Can I change variable name through automated name generation? 2. Can I assign events and such to an anonymously added menuItem after it has been added to a menu?
variable names are used by the developer, not the JVM.
tell me...what good would it do to dynamically come up with a name like 'component2' in a loop. You don't have any way to reference that variable later, unless you (again) dynamically regenerate the names, which just seems like a bad idea on so many levels.
If you want a bunch of objects, that is what a collection is for. An ArrayList will hold all of them, and let you reference them later. Or you could use a Map. or a linked list...or any of the other dozen (or so) collection types, which makes much more sense than programatically coming up with a variable name on the fly.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Mikael Saltzman wrote:2. Can I assign events and such to an anonymously added menuItem after it has been added to a menu?
Sure you can. Remember that you're adding a reference to the JMenuItemobject to the menu, not a reference to a variable. So if there's a JMenu method which returns that reference, then simply assign the reference to a local variable and do whatever you like with it. The fact that elsewhere in the program you assigned that reference to some other variable means nothing.
Joined: Dec 07, 2012
Thanks both of you! Crystal clear! Classic mistake to start to think of variables (pointing at objects) as containers rather than object references. JMenu's getItem() method saved me a lot of code here, which is in line with the suggestion to look into the container class' ability to access contained objects through get methods.