【问题标题】:Typing effect to text in JTextAreaJTextArea 中文本的打字效果
【发布时间】:2014-10-30 12:02:11
【问题描述】:

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

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

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

【问题讨论】:

    标签: java swing delay jtextarea


    【解决方案1】:

    请改用javax.swing.Timer。继续参考JTextArea 实例和字符索引。在每个actionPerformed() 调用中,将当前字符附加到JTextArea。当 char 索引等于 char 数组长度时停止 Timer

    【讨论】:

    • 举例说明,让初学者理解
    【解决方案2】:

    尝试使用这个,用这个while替换你的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++;
    }
    

    【讨论】:

    • 是的,事实上我刚刚编辑了它,我错过了删除 for 循环行。但现在它可以工作了。
    • 不,它不起作用。 JTextArea#append 应该在 EDT 上调用,所以你的 Thread.sleep 调用会阻塞 EDT 并确保不会发生重绘
    【解决方案3】:
    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();
    }
    

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

    【讨论】:

    • Thread.sleep on Event Dispatch Thread 从来都不是一个好的解决方案,因为它会阻塞 UI
    • 我已经更新了代码。现在它不会阻塞用户界面了。
    猜你喜欢
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2018-03-14
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多