1

I am creating a hangman game using a java gui. I was wondering how to add a JLabel to an array list and to a JPanel. The problem is that the JLabels have to be added according to the length of the word. I don't know how to add a JLabel if it doesn't have a predefined name. The code is below:

for(int x = 1; x <= selectedWord.wordLength; x++){
      wordSpacesPanel.add(new JLabel("?  "));

} 

If you need more than the above code just ask. Any help is appreciated as I have been trying to figure this out for a few hours. Thanks Again.

1 Answer 1

3

Just create a local JLabel variable in the loop:

for(int x = 1; x <= selectedWord.wordLength; x++){
   JLabel localLabel = new JLabel("?   ");
   wordSpacesPanel.add(localLabel);
   labelArrayList.add(localLabel);
} 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick response! Will this work if I wanted to find the third JLabel that was printed out, or any JLabel in the ArrayList for that matter?
@user2280906: a more general question is: can you get the 3rd item in an ArrayList? And: can you iterate through an ArrayList with a for loop? I think that you already know that the obvious answer to both questions is "yes".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.