2014-10-30 53 views
2

我正在制作一个具有JTextArea的程序。我正在使用append()方法向其添加文本。我希望文本可以像某人在JTextArea中输入一样,即它应该输入一个字符,然后等待400毫秒,再输入下一个字符,然后再等待,等等。 这是我的代码:在JTextArea中输入文字效果

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){} 
    } 
} 

但这不起作用。它等待几秒钟,不显示任何内容,然后一次显示整个文本。请建议。

回答

4

使用javax.swing.Timer代替。继续参考JTextArea实例和char索引。在每个actionPerformed()调用上追加当前字符到JTextArea。当字符索引等于char数组长度停止计时器

+0

解释一个例子,以便初学者可以理解 – Vijay 2016-05-29 07:53:34

0

尝试使用这个,这个,而取代你的for循环:

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++; 
} 

编辑:

我只是编辑,以避免线程问题:

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++; 
} 
+2

它会阻止EDT。 – StanislavL 2014-10-30 12:11:22

+0

此解决方案不起作用。 – zubergu 2014-10-30 12:37:21

+0

是的,事实上,我只是编辑它,我错过了删除for循环线。但现在它的工作。 – 2014-10-30 13:11:03

-2
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(); 
} 

检查上面的代码将正常工作。

+0

事件调度线程上的'Thread.sleep'从来不是一个好的解决方案,因为它阻止了UI – Robin 2014-10-30 14:49:52

+0

我已经更新了代码。现在它不会阻止用户界面。 – 2014-10-31 07:27:13