2014-10-30 71 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