问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/62128170/how-to-loop-text-of-an-element-in-jlabel