简体   繁体   中英

How to loop text of an element in JLabel?

I'm having a problem with loops. How does this loop, loop through different values and display all values on the label, rather than displaying the last value of the array on the label?

Image of code for loop .

This below code is just copied(written) from your screenshot. which has the minor bug.

sinhvien sv = new sinhvien();
sv.setdata("CC",12);
  sv.setdata("CL",14);
   sv.setdata("CCCL",16);

     s1.add(sv);

As you have only created one instance of sv and setting the value 3 times. Value CCCL override all other two previous values.

sv.setdata("CCCL",16);

So, at line

s1.add(sv);

you are actually adding only one instance of sinhvien into the array list.

Debugging: Check the array list size that will give you some clue why you are getting this behaviour. Use the below code after the loop.

//Code to get ArrayList size
System.out.println(sv1.size());

Whenever adding items into ArrayList make sure each item has a new instance of the sinhvien.

Please try the below code,

sinhvien sv = new sinhvien();
sv.setdata("CC",12);
sv1.add(sv);

sv = new sinhvien();
sv.setdata("CL",14);
sv1.add(sv);

sv = new sinhvien();
sv.setdata("CCCL",16);
sv1.add(sv);

Note: Replace above code inside the jButton1ActionPerormed method and before the for a loop. This is nowhere loop issue. It is assignment issue.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM