0

I am trying to continually create JLabels for every name in an ArrayList PantryNames. Here is my current code:

for(int i = 0; i < FoodApp.getPantryNames().size(); i++){
        JLabel lblNewLabel = new JLabel((String) FoodApp.getPantryNames().get(i));
        contentPane.add(lblNewLabel, BorderLayout.WEST);
    }

I want the lblNewLabel to be set to "ingredient" + (i + 1). For example, the first food would be ingredient1 and so on. Additionally, in the contentPane, lblNewLabel would have to be ingredient + (i + 1). Thanks!

Nmolby
  • 1
  • 1
  • Trying to create dynamically named variables not the Java way, and it puts way too much importance on variable names than they should be given. They almost don't exist in Java code, and far more important are **references** to objects. Please see [this similar question](http://stackoverflow.com/questions/6729605/assigning-variables-with-dynamic-names-in-java) for more. – Hovercraft Full Of Eels Oct 13 '16 at 17:23

1 Answers1

0

That's not how variables work in Java, you can't dynamically set variable names like that. Instead I would use a List<JLabel>.

ArrayList<JLabel> labels = new ArrayList<JLabel>();
for(int i = 0; i < FoodApp.getPantryNames().size(); i++){
    JLabel temp = new JLabel((String) FoodApp.getPantryNames().get(i));
    labels.add(temp);
    contentPane.add(temp, BorderLayout.WEST);
}

Alternatively you could just call contentPane.getComponents() whenever you need the labels again.

apetranzilla
  • 5,331
  • 27
  • 34