问题
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!
回答1:
Like this:
StringBuilder sb = new StringBuilder();
for (Integer i : list) {
sb.append(i == null ? "" : i.toString());
}
lbl.setText(sb.toString());
回答2:
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);
}
回答3:
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() );
回答4:
Apache Commons Lang to the rescue (again) with StringUtils.join() (in different flavours).
回答5:
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.
来源:https://stackoverflow.com/questions/1532064/arraylist-content-to-jlabel