I need to display output to a JTextArea one character at a time, with a slight delay between each character. My attempt is as follows:
private static void printInput(final String input)
{
Timer timer = new Timer(60,new ActionListener(){
public void actionPerformed(ActionEvent e)
{
for(int i = 0; i<input.length(); i++)
{
messageArea.append(Character.toString(input.charAt(i)));
}
}
});
}
There are similar questions however I could not find one with an example I could use to figure out my problem
A
Timer
is a pseudo loop, that it is, it triggers an cycle after a predefined delay, each cycle is an iteration of the loop and each iteration you need to update the UI and update the iterator value.Now, because I don't like working in the
static
context, the first thing I suggest is you wrap up the basic concept into a separate class. This way you can easily encapsulate the stateSo, this is pretty basic, all this does is, using a
Timer
, check to see if there are any more characters that need to be printed, if there is, it takes the next character and appends it to the text area and updates the iterator value. If we're at the end of the text, it will stop theTimer
(ie, the exit condition)