How to display an array to the user

I am trying to display the contents of an ordered array in something like JTextField.

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

      

This will not work for two reasons. First minor reason: if the length of the array is 4 then jtextfield is reset 4 times rather than adding each element to the last. Second reason: JTextField only accepts strings. I can't find anything I can use in Swing that will allow me to display integers to the user. Any help?

0


source to share


2 answers


Quick and dirty answer

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

      

The right way

First, calling a member variable is JTextField

probably not smart. Since the class is already called like, it will confuse readers. The naming conventions for Java state member variables are similar to, for example myTextField

. (note: original question modified).

Custom format

Note that you can convert any number to a string simply by doing "" + number

. If you have a lot of lines, consider using a string builder as it is faster and won't update the GUI element multiple times: (also fixes the initial ", "

to the first element, 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]

.

+8


source


You can concatenate all of these integers into a string and then present that value in a text box.

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 also use JTextArea instead of a textbox.

0


source







All Articles