我正在製作一個文本冒險遊戲,並遇到了一個問題,我無法以我想要的方式獲取一些文本顯示。當輸入一些單詞時,玩家可以開始引入新房間。我想要這個介紹有「打字機」的效果。此事件需要在我的程序ActionPerformed方法中進行。例如,當用戶鍵入「移動」然後點擊輸入時,我想讓結果文本一次打印一個字符。使用計時器在JTextArea中實現打字機效果?
這是當前的方法我用的actionPerformed之外實現這樣的效果:我怎樣才能得到類似的方法與使用Timer類的工作,所以它不會阻止我的線程
public void slowPrint(String message, long millisPerChar)
{
//makes it so that the player cannot input while the text is being displayed
userinput.setEditable(false);
String o;
for (int i = 0; i < message.length(); i++)
{
//adds each letter one-by-one
o = "" + message.charAt(i);
output.append(o);
//moves the JTextArea to the bottom
output.setCaretPosition (output.getDocument().getLength());
//delay so that you can see each letter being added
try {
Thread.sleep(millisPerChar);;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace(); }
}
//after the text is displayed allow the user to input again
userinput.setEditable(true);
}
從更新GUI。
這就是我的行動進行貌似相關的方法:
public void actionPerformed(ActionEvent e)
{
s = userinput.getText();
output.append("\n");
userinput.setText("");
for (int i = 0; i<whatRoom.length; i++)
{
if (whatRoom[i])
{
switch(i)
{
case 0:
controlOne(s);
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
}
}
}
與「controlOne()」方法:
private void controlOne(String s)
{
if(one.getHasLight() == true)
{
if(!one.getPushYes())
{
output.append(one.dealWithLight(s, output));
}
else output.append(one.commands(s));
}
else output.append(one.commands(s));
}
相反,附加的一切我都希望使用時間類似於我的「slowPrint」方法。
希望這有一些道理,任何幫助將不勝感激。