Reputation: 6077
I am making a program that has a JTextArea. I am using the append() method to add text to it. I want the text to be like someone is typing in the JTextArea, i.e. it should type one character, then wait for 400 milliseconds, the the next character, then again wait, and so on. This is my code:
public void type(String s)
{
char[] ch = s.toCharArray();
for(int i = 0; i < ch.length; i++)
{
// ta is the JTextArea
ta.append(ch[i]+"");
try{new Robot().delay(400);}catch(Exception e){}
}
}
But this is not working. It waits for some seconds, without displaying anything, and then displays the whole text at once. Please suggest.
Upvotes: 2
Views: 870
Reputation: 32145
Try using this, replace your for loop by this while:
int i=0;
while(i<s.length())
{
// ta is the JTextArea
ta.append(s.charAt(i));
try
{
Thread.sleep(400);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
i++;
}
Edit:
I just edited it to avoid thread problem:
int i=0;
while(i<s.length())
{
// ta is the JTextArea
ta.append(s.charAt(i));
try {
TimeUnit.MILLISECONDS.sleep(400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
Upvotes: 0
Reputation: 130
public void type(final String s)
{
new Thread(){
public void run(){
for(int i = 0; i < s.length(); i++)
{
// ta is the JTextArea
ta.append(""+s.charAt(i));
try{Thread.sleep(400);}catch(Exception e){}
}
}
}.start();
}
check above code will work fine.
Upvotes: -2
Reputation: 57421
Use javax.swing.Timer
instead. Keep reference to the JTextArea
instance and char index. On each actionPerformed()
call append current char to the JTextArea
. When the char index equals to the char array length stop the Timer
Upvotes: 4