0

I am currently facing an issue where I have an ArrayList of answers to a question and I am trying to print out each answer to a JLabel as this will display the question being added to the question bank.

The problem is it will only print one answer and there could be 5 answers stored in the array. It is printing it to the console I have tried putting this.add(answerLabel); inside the for loop and outside.

Am I approaching this the best way?

answerLabel = new JLabel();
answerLabel.setBounds(100, 100, 300, 300);

for (int i = 0; i < answers.size(); i++) {
    answerLabel.setText("Answer " + i + ": " + answers.get(i));
    System.out.println("Answer " + i + ": " + answers.get(i));
    this.add(answerLabel);
}
IAmAndy
  • 121
  • 2
  • 12

2 Answers2

4

What you'll need to consider is to create a new instance of JLabel once you've added the previous one

answerLabel = new JLabel();
answerLabel.setBounds(100, 100, 300, 300);

for (int i = 0; i < answers.size(); i++) {
    answerLabel.setText("Answer " + i + ": " + answers.get(i));
    System.out.println("Answer " + i + ": " + answers.get(i));
    this.add(answerLabel);
    answerLabel = new JLabel();
    answerLabel.setBounds(100, 100, 300, 300);
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
2

There are some issues with your code:

  1. setBounds tells us that you're using null-layout, see: Why is it frowned upon to use a null layout in Swing? and if that's still not enough to show what the problems with using it are, here's an example of those. Instead use layout managers and let Swing do the calculations for you

  2. You're calling setText on your JLabel everytime your for does an iteration, this is overriding what you had on the previous iteration, so you have 2 options:

  • Create a new instance of a JLabel on every iteration

    JPanel pane = new JPanel();
    pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
    
    for (int i = 0; i < answers.size(); i++) {
        answerLabel = new JLabel();
        answerLabel.setText("Answer " + i + ": " + answers.get(i));
        pane.add(answerLabel);
    }
    this.add(pane);
    
  • Create a single instance of String and append all your text to it, then call setText on your JLabel once with the value of that String

    String text = "";
    for (int i = 0; i < answers.size(); i++) {
        text += "Answer " + i + ": " + answers.get(i) + "\n"; //Replace this for a StringBuilder, just making this an example
    }
    answerLabel.setText(text);
    this.add(answerLabel);
    
Frakcool
  • 10,915
  • 9
  • 50
  • 89