CaldwellYSR
CaldwellYSR

Reputation: 3196

append a char to a JTextArea

So I'm working on making a class that will "type" letters into a JTextArea, pausing between each letter to make it look like someone is typing. The only way I can come up with is using output.append(char) in a loop with a pause. The only problem... you can only append Strings to JTextAreas.

So is there any way to convert a char to a string so that I can append it letter by letter???

Here is my code so far:

import objectdraw.*;
import java.awt.*;
import javax.swing.*;

public class TypeWriter extends ActiveObject
                        implements Drawable {

  private char [] letter;
  private JTextArea cp;

  public TypeWriter(String sentence, JTextArea console) {

    /* break string into characters and save the console
     * for later use
     */
    letter = new char[sentence.length()];
    cp = console;

    for(int i=0; i<sentence.length(); i++) {
      letter[i] = sentence.charAt(i);
    }

    start();

  }

  public void run() {

    // append each letter, pausing between them
    for( char s : letter ) {
      cp.append(new String(s));
      pause(50);
    }

  }

  /* More methods for the 
   * Drawable interface...
   */

}

Upvotes: 3

Views: 1499

Answers (2)

lancegerday
lancegerday

Reputation: 762

Use the String(char[] value) constructor so

String s = "";
s += Character.toString('s');

Upvotes: 3

Brian Roach
Brian Roach

Reputation: 76908

Don't use characters.

String foo = "This is a String";
for (int i = 0; i < foo.length(); i++)
{
    String subString = foo.substring(i, i+1);
    cp.append(subString);
    pause(50);
}

Upvotes: 2

Related Questions