JohnD
JohnD

Reputation: 23

How to do I print an arraylist to a JTextArea?

I can't seem to figure out how to print an arrayList<String> to a JTextArea and have tried using both append() and setText(). I have also tried to create a method which prints out the ArrayList through a loop, but it can't be added to the JTextArea because it is not of type String.

An applicant is supposed to take a student profile (name, grade, university selections) and add it to the ArrayList<String> Applicants. This is done through a JButton if it holds true for the following if statement:

if (studentsAverage > 74 && validInput && studentsAverage < 100) {

    studentChoices.addAll(uniOptions.getSelectedValuesList());
    person = new Student (namePromptTF.getText(), averagePromptTF.getText(),Applicants, studentChoices);
    arrayCount++;
    numberOfApplicants.setText(arrayCount +"/" +100+"students");                    

    person.printProfile(); //dont need
    person.studentProfileSort(); // dont need


    displayAllApplicants.append(person.returnProfile());

    Applicants.add(person);

The array is passed to a Student object that holds:

private ArrayList<Student> ApplicantArray;

ApplicantArray is then sorted through this method:

void studentProfileSort() {
    Student profileLine = null;

    int numberOfStudents = ApplicantArray.size();   
    ArrayList<Student> displayAllSorted = new ArrayList<Student>();

    for(int i = 1; i<numberOfStudents - 1; i++){
        for(int j = 0; j<(numberOfStudents - i); j++) {

            if(ApplicantArray.get(i).getFamilyName().compareTo(ApplicantArray.get(i).getFamilyName())>0){
                ApplicantArray.set(j, ApplicantArray.get(i));
            }
        }

        ApplicantArray.get(i).returnProfile();          
    }
}

Is there a way to have a return statement inside of a loop so that I can change my method to a String type?

Upvotes: 0

Views: 510

Answers (1)

Jakob Probst
Jakob Probst

Reputation: 87

At first your sorting algorithm does not seem to work

ApplicantArray.get(i).getFamilyName().compareTo(ApplicantArray.get(i).getFamilyName())

You compare the value with it self and this results always in 0. Even if this would work, in the next line you override the array by setting a value rather than swapping the two values or setting to a new ArrayList.

But if everything works, this is how you could print those students:

StringBuilder b = new StringBuilder();
for (Student student : applicantArray) {
    b.append(student + "\n"); // this if you implemented toString() in Student
    b.append(student.getFamilyName() + ' ' + student.getFirstName() + "\n"); // or something like this
}
textArea.setText(b.toString());

P.S.: you should never use UpperCamelCase for variables or parameters, use lowerCamelCase instead (e.g. ApplicantArray -> applicantArray)

Upvotes: 1

Related Questions