ArrayList content to JLabel

为君一笑 提交于 2019-12-06 14:58:38

Like this:

StringBuilder sb = new StringBuilder();
for (Integer i : list) {
    sb.append(i == null ? "" : i.toString());
}
lbl.setText(sb.toString());
private static String fromListToString(List<Integer> input) {
    StringBuilder sb = new StringBuilder();
    for (Integer num : input) {
        sb.append(num);
    }
    return sb.toString();
}

public static void main(String[] args) {
    JFrame f = new JFrame();
    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(3);
    list.add(4);
    list.add(9);
    list.add(10);
    f.getContentPane().add(new JLabel(fromListToString(list)));
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}

Example:

    List<Integer> list = Arrays.asList( 1, 3, 5, 7 );

    StringBuilder joined = new StringBuilder();
    for (Integer number : list) {
        joined.append( number );
    }
    new JLabel().setText( joined.toString() );

Apache Commons Lang to the rescue (again) with StringUtils.join() (in different flavours).

You start with an empty string (or StringBuilder). Then you iterate through the items of the list, adding each item to the string. Then you set the string as the JLabel's text.

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