Java 为 JTextArea 添加打字机效果 [英] Java add Typewriter effect to JTextArea

查看:33
本文介绍了Java 为 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

推荐答案

Timer 是一个伪循环,也就是说,它在预定义的延迟后触发一个循环,每个循环是循环和每次迭代都需要更新 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();
    }

}

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

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 为 JTextArea 添加打字机效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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