I am learning programming with Java through a textbook. A programming exercise asks you to:
(Swing common features) Display a frame that contains six labels. Set th
I would suggest that if you are learning to program for professional reasons then you should follow as it given in the book. Because in bigger projects (if you might be working on one in future), this practice is very common and as you said, readability and a variable name. Say it is like a convention.
It seems that you have answered the question yourself. Yes you would need references (what you call a variable name) if you there is a requirement to manipulate the labels (change attributes) on event generations. But yes if there is no such requirement, in that case your method of using an Array or List is clean and requires less code writing effort.
in my opinion better practice would be create method Jlabel createLabel(String text, Color foregroundColor)
and use it in loop to create labels
I can provide you a third answer. Create a method that takes a JLabel
and configures it. That way you could use either of the other two and reduce your code complexity.
The answer is, it depends. It depends on what it is you want to achieve.
If you are making lots of changes, repeatedly to the same serious of components, such as you are here, I might be tempted to use a simple List
or array. This is particularly useful if the number of elements is dynamic and or only accessiable internally to the class.
If, on the other hand you want to change or update the state of the components externally, it's normally easier to provide named access to the components. Yes, you could provide a method that uses a int
parameter, but then you start running into issues with always having to validate the parameter :P
So I guess, the question is, what is it you need to achieve?
Collections or arrays would be my preference. Making changes or adding additional fields would be easy. In your first example, you could do everything in one loop. You don't need a separate loop per attribute. Your code would be tiny after removing the extra loops.