I have 8 JLabels
that i initially want to be invisible. The jlabels
start from 25 and go 32. _(ie jLabel25 ---> jLabel32)_
Instead of making them invisible one by one i was thinking of using a for loop that could make them invisible by following these lines of code:
for( int i = 25 ; i <= 32 ; i++ ) {
jLabel(i).setVisible(false);
}
But i get an obvious error that says "Cannot find symbol, method--> jLabel(int) "
What should i do to avoid writing 8 statements asking to make each label
invisible?
Put the labels into a common collection, and iterate through that.
Collection<JLabel> myLabels = new ArrayList<JLabel>();
myLabels.add(jLabel25); // .. and so on
for (JLabel label : myLabels) {
label.setVisible(false);
}
No, I do not think that is possible, you will have to write the full name out each time:
jLabel25.setVisible(false);
Another possible solution is put the labels in a array or list, and iterate through the list/array and set it to false.
for(JLabel label :listOfLabels)
{
label.setVisible(false);
}
Can't you put them in a List?
List<JLabel> labels = Arrays.asList(jLabel25, jLabel26, /*rest of 'em here*/);
for(JLabel label : labels) {
label.setVisible(false);
}
If you want to convince your co-workers you're mad or would rather be programming in another language, you could use reflection.
for(Field labelField : getClass().getFields()) {
String name = label.getName();
if(name.startsWith("jLabel") && name.length == 8 && indexBetween(name.substring(7, 9), 25, 32)) {
JLabel label = (JLabel) labelField.get(this);
label.setVisible(false);
}
}
This only works if the labels are fields on the current class, obviously.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.