aspose file tools*
The moose likes Beginning Java and the fly likes Variable name generation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variable name generation" Watch "Variable name generation" New topic
Author

Variable name generation

Mikael Saltzman
Greenhorn

Joined: Dec 07, 2012
Posts: 9
Hi!

Suppose I have a variable: .

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?

Thanks for reading!
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11477
    
  16

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
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18901
    
    8

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 JMenuItem object 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.
Mikael Saltzman
Greenhorn

Joined: Dec 07, 2012
Posts: 9
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.
 
Don't get me started about those stupid light bulbs.
 
subject: Variable name generation