How to loop text of an element in JLabel?

老子叫甜甜 提交于 2020-06-27 04:07:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!