简体   繁体   中英

How to output a Vector into a JTextArea in a JFrame?

Let's just say i have a Vector of Strings, and I want to output them to a JTextArea. What methods should I use?

I was thinking of using a for loop with:

Vector temp = new Vector();
String temp = list.getText(i) + '\n';
textArea.setText(temp);

Which I know does not work. I heard of append() doing something related, but wasn't sure what to do. Any tips?

well, you're close. I think what you meant was...

Vector<String> list;
...
String tmp = "";
for( int i = 0 ; i < list.size(); i++ )
{
   tmp = tmp + list.get(i) + "\n"; 
}
textArea.setText( tmp );

And in regard to your other comment, yes, whenever running a loop that appends a string value, you're going to want to use StringBuffer instead of string...

Vector<String> list;
...
StringBuffer tmp = new StringBuffer();
for( int i = 0 ; i < list.size(); i++ )
{
    tmp.append( list.get(i) + "\n");
}
textArea.setText( tmp.toString() );

Firstly, Vector is a synchronized container. What this means is that it's thread safe. Unless you are planning to access it using multiple threads, there's little point and you're better off just using an ArrayList .

Secondly, unless you're using a really ancient version of Java, you'll want to make sure you're using a parametrised container, ie:

List<String> list = new ArrayList<String>();

To check for methods on a JTextArea, the Java API is your friend.

You'll also need to loop over your container to append all its elements as well.

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