Thomas Richmond Thomas Richmond - 1 month ago 11
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 {
displayArea.setText("");
String s = "";
for(int i = 0; i<input.length(); i++) {
s += input.substring(i, i+1);
displayArea.setText(textToDisplay);
Thread.sleep(40);
displayArea.update(displayArea.getGraphics());
}
}


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;
displayArea.setText("");
timer = new Timer(30, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
s[0] = input.substring(i[0], i[0]+1);
i[0]++;
displayArea.append(s[0]);
if(displayArea.getText().equals(input))
timer.stop();
}
});
timer.start();
}

Answer
displayArea.update(displayArea.getGraphics());

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.

displayArea.setText(textToDisplay);

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.