简体   繁体   中英

ArrayList of type Object to display output in JTextArea

I have this assignment i'm working for in college, we have to do a GUI asking input from the user and display the final output (an ArrayList of type Object) in JTextArea, they are in separate classes. Problem is it's only displaying the return from the toString() method I overwritten. Here's my code, this is the toString method in the non GUI class:

  @Override
    public String toString() {



        int u = 1;

        System.out.println("Team " + name + " has " + players.size() + " players");
        for(int i=0; i< players.size();i++)  {
            System.out.print(u++ + ".");
            System.out.println(players.get(i));
        }
              return "Team " + name + " has " + size + " players";

}
        }

this is the JTextArea calling it from the GUI class:

public class GUI extends Team  {    
        //buttons 
        /constructor
      public  GUI() {

                frame = new JFrame("Team Manager");
                frame.setLayout(new BorderLayout());
                frame.setSize(300, 300);

          jta = new JTextArea(super.toString());
          frame.add(jta, BorderLayout.CENTER);  }

Only the return value of toString() is displaying in the JTextArea, how do I make so that it displays the loop line by line? I have tried making a foreach loop and appending the results, also tried setText() and append() but they don't take type objects, how should I go about doing this?

              for ( MyObject o : ArrayList1) {
                textarea1.append( o.toString() );
                  }

If you want to separate text into lines use textArea.setLineWrap(true);

Also don't use setText() as said @SHA33. As I know this method simply change text in JTextArea. Use append method. If you want to separate text also you can append \\n at the end of each line.

Also you can look at this articles:

  1. How to Use Text Areas
  2. Class JTextArea

尝试在for循环内的toString()中返回结果,并改用textarea1.setText(...)。

How about this?

String str = "";
for ( MyObject o : ArrayList1) {
    str = str + o.toString();
}
textarea1.setText(str);

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