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 yo开发者_如何学Cu in advance for any help.
EDIT: Thank you all, ofcourse i should have thought about append. Anyways, thanks all!
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.
精彩评论