1

I'm trying to print arraylist contents into Jlabel but the problem is that it only shows the last integer I add, if somebody can help me please?

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    for(int i = 0; i < list.size(); i++){
        jLabel1.setText(list.toString());
    }

}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    list = new ArrayList<Integer>();
    int a = Integer.parseInt(jTextField1.getText());
    list.add(a);
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

2 Answers2

1

You don't need to place addition of list.toString in a loop for every element of list as you are doing:

for(int i = 0; i < list.size(); i++){
   jLabel1.setText(list.toString());
}

The above loop should be simply replaced by

jLabel1.setText(list.toString());

This will add all the contents of list to the jLabel1

Why are you getting only the last element? As you are creating a new ArrayList every time in method jButton2ActionPerformed, and subsequently adding only one element to this newly created list, you get only the last element in your jLabel1

You need to have a list that is created only once (initialized only once) and each call of the jButton2ActionPerformed should add element to the existing list (instead of creating a new every time).

Lavish Kothari
  • 2,211
  • 21
  • 29
1

Your code to set the text of the JLabel to a text containing all the contents of the list is correct. If only one number is displayed it’s either because the label is too small or because the list only contains one number.

You don’t need the for loop though, since list.toString() generates a string with all contents even when you just call it once. But it should work with multiple calls too, that is, with the for loop.

Your issue is that you’re creating a new list for each button press. This causes you to lose all contents of the previous list and only keep the new number added. So just don’t do that. Create the list once when your program starts, or when it’s appropriate.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161