I have 10 JLabels which I want to have the same border. It is a number that is manageable by hand but to grow as a programmer I want to know if there is a way to make this easier.
I have tried with a for each loop that goes true all the components of the panel the labels are on, and then use the method setBorder(...). But this doesn’t work obviously because the objects are recognized as Components instead of JLabels.
How do I automate the border assignment to a JLabel?
The answer provided by @Atreys will suffice, but there’s more than one way to skin a cat. Another option would be to create a class that extends
JLabeland assigns a border within its constructor. Therefore, all instances will have the same border, as per your request. This will also avoid having to clumsily iterate over a collection ofComponents, use theinstanceofoperator, and then typecast, which isn’t really OOP.Addendum:
And if you wanted to avoid the verbosity of having to type
new BorderedJLabel()for each newBorderedJLabelinstance, you could peruse a static factory method, as suchGiven this design, you’ll be able to create new
BorderedJLabelinstances more succinctly by simply typingBorderedJLabel.newInstance().