Thread.sleep()有时不工作

nru*_*n29 0 java

为糟糕的头衔道歉.我正在开发一个使用JTextPane作为主文本视图的游戏.我使用以下代码打印到窗格:

public void write(String txt, MessageType t) {
        try {
            for (char c : txt.toCharArray()) {
                text.getDocument().insertString(text.getDocument().getLength(), String.valueOf(c), t.getAttributes());
                Utils.pause(30);
            }
            text.getDocument().insertString(text.getDocument().getLength(), "\n", t.getAttributes());
        }
        catch (Exception e) { e.printStackTrace(); }
    }
Run Code Online (Sandbox Code Playgroud)

该代码一次写入一个字符,每次写入之间休眠30毫秒.然后它写一个新的行字符.如果您有兴趣,这是pause()方法:

public static void pause(int millis) {
        try { Thread.sleep(millis); }
        catch (InterruptedException e) { e.printStackTrace(); }
    }
Run Code Online (Sandbox Code Playgroud)

大多数时候,这很好.它会在每个角色之间写入一些空格,给人一种打字的印象.但是,有一个例子它不起作用.

我有一个处理输入的JTextField.我将这个KeyListener添加到它:

input.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    CommandParser.getInstance().parse(input.getText());
                    input.setText("");
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)

在CommandParser的parse()方法结束时,如果找不到命令,则该行运行:

Game.getInstance().getGUI().write("Invalid command.", GUI.MessageType.BAD);
Run Code Online (Sandbox Code Playgroud)

但是,仅对于该行,程序等待一秒,然后立即打印所有内容,而不是每30毫秒打印一个字符.为什么是这样?这与内部类有关吗?

Tim*_*m B 5

这是因为您的操作发生在EDT线程上.在您从该方法返回之前,GUI根本不会更新.您需要使用类似的东西SwingWorkerSwingTimer将更新存储到另一个线程.