Search code examples
jtextareasettext

How to go to next line while using a loop to setText in JTextArea?


This is my code

 for (int m=0; m < i ; m++){
  ta1.setText( s[m].getName().toString() + ", " + s[m].getProgramName().toString() + ", "           + s[m].getUni1() + ", " + s[m].getUni2() + ", " + s[m].getUni3() + ", " );
 }

It's supposed to print a line from an array of student ( called s) into a JTextArea ( called ta1 ). the problem is that it always only prints the last student in the array.

I need to print each student in a new line. could anyone help me sort it out?


Solution

  • When you set text on an element, the current position in the loop will take over the last one.

    Try doing this.

    String s = "";
    for(int m = 0, m <i; m++){
        s += s[m].getName.toString() + ", " + s[m].getprogramName().toString() + "\n;
    }
    ta1.setText(s);
    

    Create a string and add each entry to it then add new line to end of each entry "\n" Then do.

    ta1.setText(s);