views:

257

answers:

5

Hi all,

If i have an ArrayList of type Integer, containing numbers like 1,3,4,9,10 etc... How can i display those on a JLabel, not the sum, but all the numbers in a sequence.

So the JLabel would display, in this case: 134910

Thank you in advance for any help.

EDIT: Thank you all, ofcourse i should have thought about append. Anyways, thanks all!

+2  A: 

Like this:

StringBuilder sb = new StringBuilder();
for (Integer i : list) {
    sb.append(i == null ? "" : i.toString());
}
lbl.setText(sb.toString());
jsight
+1 neat. What's wrong with `sb.append(i)`?
OscarRyz
Is that for the null?
OscarRyz
Yeah, checking for null, since these are objects. I figured an empty string might be preferable to the text "null". :)
jsight
A: 

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.

sepp2k
+1  A: 
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);
}
Boris Pavlović
Thank you for the answer!
Jones
+1  A: 

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() );
tangens
Or even better: `ArrayList<Integer> list = Arrays.asList(1, 3, 5, 7);`
IgKh
Or even better: `List<Integer> list = Arrays.asList(1, 3, 5, 7);`
Joachim Sauer
Thanks, it really looks better this way.
tangens
Joachim: you are right of course. Thanks for the correction!
IgKh
+1  A: 

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

Brian Agnew