Java将Typewriter效果添加到JTextArea [英] Java add Typewriter effect to JTextArea

查看:92
本文介绍了Java将Typewriter效果添加到JTextArea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一次向JTextArea显示一个字符的输出,每个字符之间稍有延迟。我的尝试如下:

I need to display output to a JTextArea one character at a time, with a slight delay between each character. My attempt is as follows:

 private static void printInput(final String input)
{
        Timer timer = new Timer(60,new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                for(int i = 0; i<input.length(); i++)
                {
                    messageArea.append(Character.toString(input.charAt(i)));
                }
            }
        });
}

有类似的问题但我找不到一个我可以使用的例子找出我的问题

There are similar questions however I could not find one with an example I could use to figure out my problem

推荐答案

A 计时器是一个伪循环,就是这样,它会在预定义的延迟之后触发一个循环,每个循环都是循环的迭代,每次迭代都需要更新UI并更新迭代器值。

A Timer is a pseudo loop, that it is, it triggers an cycle after a predefined delay, each cycle is an iteration of the loop and each iteration you need to update the UI and update the iterator value.

现在,因为我不喜欢在 static 上下文中工作,我建议的第一件事是将基本概念包装到一个单独的类中。通过这种方式,您可以轻松封装状态

Now, because I don't like working in the static context, the first thing I suggest is you wrap up the basic concept into a separate class. This way you can easily encapsulate the state

public class TypeWriter {
    private Timer timer;
    private int characterIndex = 0;
    private String input;
    private JTextArea textArea;

    public TypeWriter(JTextArea textArea, String input) {
        this.textArea = textArea;
        this.input = input;
        timer = new Timer(60, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (characterIndex < input.length()) {
                    textArea.append(Character.toString(input.charAt(characterIndex)));
                    characterIndex++;
                } else {
                    stop();
                }
            }
        });
    }

    public void start() {
        textArea.setText(null);
        characterIndex = 0;
        timer.start();
    }

    public void stop() {
        timer.stop();
    }

}

所以,这是非常基本的,所有这一切,使用计时器,检查是否还有更多需要打印的字符,如果有,则需要下一个字符并将其附加到文本区域并更新迭代器值。如果我们在文本的末尾,它将停止计时器(即退出条件)

So, this is pretty basic, all this does is, using a Timer, check to see if there are any more characters that need to be printed, if there is, it takes the next character and appends it to the text area and updates the iterator value. If we're at the end of the text, it will stop the Timer (ie, the exit condition)

这篇关于Java将Typewriter效果添加到JTextArea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆