Thomas Richmond Thomas Richmond - 1 year ago 49
Java Question

Java - How to stop text from flickering when using setText() quickly

So I have been having some trouble trying to create a teletype effect for my swing program. I essentially want to update a JFrame at 40ms increments with a new letter, "typing" out a message to the user. However, it flickers a lot when I try to do this. The method is below:

public static void animateTeletype(String input, JTextArea displayArea)
throws InterruptedException {
String s = "";
for(int i = 0; i<input.length(); i++) {
s += input.substring(i, i+1);

I figure the problem stems from updating the text too fast, and it has to update more than it can handle. I am not sure how I would go about this issue, as reducing tick time will make text scroll too slowly. Any advice is appreciated!

** I've solved the problem. This is my new code:

static Timer timer = null;
public static void animateTeletype(final String input, final JTextArea displayArea) throws InterruptedException
final String[] s = new String[1];
s[0] = " ";
final int[] i = new int[1];
i[0] = 0;
timer = new Timer(30, new ActionListener()
public void actionPerformed(ActionEvent e)
s[0] = input.substring(i[0], i[0]+1);

Answer Source

Don't use the update() method. There is never any reason to do that. Get rid of that statement.

Swing components will automatically repaint themselves.


Don't uset setText(...) to add new text.

Instead you should be using:

displayArea.append( "some more text" );

Don't use Thread.sleep(40) for animation. It you want animation then use a Swing Timer to schedule the animation.

I suggest you look at other section of the tutorial for Swing basics. Maybe something like How to Use Text Fields.