简体   繁体   中英

Displaying an array list with each element on a new line?

Code:

ArrayList <Integer> marks = new ArrayList();

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
    Collections.addAll(marks, (Integer.parseInt(markInput.getText())));
    marks.add(Integer.parseInt(markInput.getText()));
    for (int j =0; j < marks.size(); j++) {
        markdisplayTextArea.setText(Integer.toString(marks.get(j)));
}

This program is supposed to display each number on a new line in a JTextArea when the user types it in and presses the "add" button.

It displays each number but only one at a time. I want each number entered to be displayed on a new line in ascending. So if the user entered 4 numbers, say, 78, 92, 54, and 21, I want them displayed like this:

21
54
78
92

You are resetting the text in every single loop in the last loop of the code.

Just write a loop to concatenate the numbers into one String (adding \\n after every number), then set the text of JTextArea to the concatenated result. Since JTextArea supports multiline text, it should be displayed correctly.

StringBuffer text = new StringBuffer();
for (Integer mark: marks) {
  text.append(mark.toString()).append('\n');
}
markdisplayTextArea.setText(text.toString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM