在JTextArea中使用Timer实现打字机效果?

2024-04-25

我正在制作一款文本冒险游戏,但遇到了一个问题,我无法按照我想要的方式显示一些文本。当输入一些单词时,玩家可以开始引入一个新房间。我希望这个介绍具有“打字机”效果。该事件需要在我的程序 ActionPerformed 方法中发生。例如,当用户键入“移动”然后按 Enter 键时,我希望生成的文本一次打印一个字符。

以下是我在 ActionPerformed 之外使用的当前方法来实现此效果:

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

我怎样才能获得类似的方法来使用 Timer 类,这样它就不会阻止我的线程更新 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”方法的方法。

希望这是有道理的,任何帮助将不胜感激。


a 的两个基本价值观Timer https://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html are

  1. 延时
  2. The ActionListener

如果您在内部创建计时器slowPrint方法,保留对它的引用很重要,以便稍后可以停止它。因此您必须添加ActionListener之后。在 - 的里面ActionListener您可以通过附加变量来跟踪当前文本位置(忘记 for 循环)。然后您只需手动检查是否已打印所有文本,并相应地停止计时器。

如果您希望最初也进行延迟,只需致电timer.setInitialDelay(delay).


以你的为例slowPrint修改方法:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.Timer;

public class Foo {

    private JTextField input;
    private JTextArea output;

    public static void main(String[] args) throws IOException {
        EventQueue.invokeLater(() -> new Foo().createAndShowGUI());
    }

    public void createAndShowGUI() {
        output = new JTextArea();
        output.setEditable(false);

        input = new JTextField();
        input.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                slowPrint("This is a test answer.\n", 100);
            }
        });

        JPanel contentPane = new JPanel(new BorderLayout(5, 5));
        contentPane.add(input, BorderLayout.NORTH);
        contentPane.add(output);

        JFrame frame = new JFrame("Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(contentPane);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }

    public void slowPrint(String message, int millisPerChar) {
        input.setEditable(false);
        input.setFocusable(false);

        Timer timer = new Timer(millisPerChar, null);
        timer.addActionListener(new ActionListener() {
            int counter = 0;

            @Override
            public void actionPerformed(ActionEvent e) {
                output.append(String.valueOf(message.charAt(counter++)));
                output.setCaretPosition(output.getDocument().getLength());
                if (counter >= message.length()) {
                    timer.stop();
                    input.setEditable(true);
                    input.setFocusable(true);
                    input.requestFocusInWindow();
                }
            }
        });
        timer.start();
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在JTextArea中使用Timer实现打字机效果? 的相关文章

随机推荐