0

I'm trying to display the contents of an ordered array in something like a JTextField.

for (int i=0; i<array.length; i++) {
    this.textField.setText(array[i]);
}

This won't work for two reasons. The first minor reason: if the array length is 4 then jtextfield is getting it's value reset 4 times rather than appending each element onto the last. Second reason: The JTextField only takes strings. I can't find anything I can use in Swing that will let me display integers to the user. Any help?

2 Answers 2

8

Quick & Dirty Answer

for (int i=0; i<array.length; i++) {
    this.myJTextField.setText(this.myJTextField.getText() + ", " + array[i]);
}

Correct Way

First, calling a member variable JTextField probably isn't wise. Since the class is already called like that, it will confuse readers. Naming conventions in Java state member variables are like myTextField for example. (note: original question changed).

User defined format

Note you can convert any number to a string by simply doing "" + number too. If you have many strings, consider using a string builder, as that's faster and won't update the GUI element multiple times: (also fixes the initial ", " before the first item, which happens above)

StringBuilder builder = new StringBuilder();
for (int i=0; i<array.length; i++) {
    builder.append(array[i]));
    if(i + 1 != array.length) 
        builder.append(", ");
}
this.myJTextField.setText(builder.toString());

Canonical array representation

Alternatively, you can use this:

this.myJTextField.setText(Arrays.toString(array));

It will look like [1, 4, 5, 6].

Sign up to request clarification or add additional context in comments.

Comments

0

You can concatenate all those integers into a string the then present that value in the textfield.

StringBuilder sb = new StringBuilder();
for( int i : array ) {  // <-- alternative way to iterate the array
     sb.append( i );
     sb.append( ", " );
}

sb.delete(sb.length()-2, sb.length()-1); // trim the extra ","
textField.setText( sb.toString() );

You can use a JTextArea instead of the textfield too.

2 Comments

You'll need to trim off the extra ", " at the end.
Ahh yeap.. 1,2,3,4, => 1,2,3,4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.