Java线程不能正确使用JTextArea

Java线程不能正确使用JTextArea,java,string,multithreading,jtextarea,Java,String,Multithreading,Jtextarea,在Java中,我目前正在创建一个登录/注册程序(希望将来扩展它),但遇到了一个问题 我正试图让文本以动画打字机风格的方式出现在屏幕上 当我运行类的main方法时,文本显示得很好,当我在keylistener中运行它时,它失败并等待文本出现,然后更新框架以便我可以看到它 源代码如下: Login.class public class Login implements KeyListener { int BACK_WIDTH = java.awt.Toolkit.getDefaultToolkit

在Java中,我目前正在创建一个登录/注册程序(希望将来扩展它),但遇到了一个问题

我正试图让文本以动画打字机风格的方式出现在屏幕上

当我运行类的main方法时,文本显示得很好,当我在keylistener中运行它时,它失败并等待文本出现,然后更新框架以便我可以看到它

源代码如下:

Login.class

public class Login implements KeyListener {

int BACK_WIDTH = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
int BACK_HEIGHT = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;

JFrame back_frame = new JFrame();

LoginTerminal login = new LoginTerminal();

public Login() {
    back_frame.setSize(BACK_WIDTH, BACK_HEIGHT);
    back_frame.setLocation(0, 0);
    back_frame.getContentPane().setBackground(Color.BLACK);
    back_frame.setUndecorated(true);
    //back_frame.setVisible(true);

    back_frame.addKeyListener(this);
    login.addKeyListener(this);
    login.setLocationRelativeTo(null);
    login.setVisible(true);
    login.field.addKeyListener(this);

    login.slowPrint("Please login to continue...\n"
               + "Type 'help' for more information.\n");
}

public void keyPressed(KeyEvent e) {
    int i = e.getKeyCode();

    if(i == KeyEvent.VK_ESCAPE) {
        System.exit(0);
    }

    if(i == KeyEvent.VK_ENTER) {
        login.slowPrint("\nCommands\n"
                 + "-----------\n"
                 + "register\n"
                 + "login\n");
    }
}

public void keyReleased(KeyEvent e) {}

public void keyTyped(KeyEvent e) {}

}
public class LoginTerminal implements KeyListener {

CustomFrame frame = new CustomFrame(Types.TERMINAL);

JTextArea log = new JTextArea();
public JTextField field = new JTextField();

public void setVisible(boolean bool) {
    frame.setVisible(bool);
}

public void addKeyListener(KeyListener listener) {
    frame.addKeyListener(listener);
}

public void slowPrint(String str) {
    for(int i = 0; i < str.length(); i++) {
        log.append("" + str.charAt(i));

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (i == str.length() - 1) {
            log.append("\n");
        }
    }
}

public void setLocation(int x, int y) {
    frame.setLocation(x, y);
}

public void setLocationRelativeTo(Component c) {
    frame.setLocationRelativeTo(c);
}

public LoginTerminal() {
    try {

        InputStream is = LoginTerminal.class.getResourceAsStream("/fonts/dungeon.TTF");
        Font font = Font.createFont(Font.TRUETYPE_FONT, is);
        font = font.deriveFont(Font.PLAIN, 10);

        frame.add(field);
        frame.add(log);

        log.setBackground(Color.BLACK);
        log.setForeground(Color.WHITE);
        log.setWrapStyleWord(true);
        log.setLineWrap(true);
        log.setBounds(4, 20 + 4, frame.getWidth() - 8, frame.getHeight() - 50);
        log.setFont(font);
        log.setEditable(false);
        log.setCaretColor(Color.BLACK);

        field.setBackground(Color.BLACK);
        field.setForeground(Color.WHITE);
        field.setBounds(2, frame.getHeight() - 23, frame.getWidth() - 5, 20);
        field.setFont(font);
        field.setCaretColor(Color.BLACK);
        field.addKeyListener(this);
        field.setText("  >  ");

    } catch (FontFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void dumpToLog() {
    log.append(field.getText() + "\n");
    field.setText("  >  ");
}

public void keyPressed(KeyEvent e) {
    int i = e.getKeyCode();

    if(i == KeyEvent.VK_ENTER && field.isFocusOwner()) {
        if(field.getText().equals("  >  HELP") || field.getText().equals("  >  help")) {
            dumpToLog();


        } else {
            dumpToLog();
        }
    }


    if(!field.getText().startsWith("  >  ")) {
        field.setText("  >  ");
    }
}

public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}

}
public class Main {

    public static void main(String[] args) {
        new Login();
    }

}
LoginTerminal.class

public class Login implements KeyListener {

int BACK_WIDTH = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
int BACK_HEIGHT = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;

JFrame back_frame = new JFrame();

LoginTerminal login = new LoginTerminal();

public Login() {
    back_frame.setSize(BACK_WIDTH, BACK_HEIGHT);
    back_frame.setLocation(0, 0);
    back_frame.getContentPane().setBackground(Color.BLACK);
    back_frame.setUndecorated(true);
    //back_frame.setVisible(true);

    back_frame.addKeyListener(this);
    login.addKeyListener(this);
    login.setLocationRelativeTo(null);
    login.setVisible(true);
    login.field.addKeyListener(this);

    login.slowPrint("Please login to continue...\n"
               + "Type 'help' for more information.\n");
}

public void keyPressed(KeyEvent e) {
    int i = e.getKeyCode();

    if(i == KeyEvent.VK_ESCAPE) {
        System.exit(0);
    }

    if(i == KeyEvent.VK_ENTER) {
        login.slowPrint("\nCommands\n"
                 + "-----------\n"
                 + "register\n"
                 + "login\n");
    }
}

public void keyReleased(KeyEvent e) {}

public void keyTyped(KeyEvent e) {}

}
public class LoginTerminal implements KeyListener {

CustomFrame frame = new CustomFrame(Types.TERMINAL);

JTextArea log = new JTextArea();
public JTextField field = new JTextField();

public void setVisible(boolean bool) {
    frame.setVisible(bool);
}

public void addKeyListener(KeyListener listener) {
    frame.addKeyListener(listener);
}

public void slowPrint(String str) {
    for(int i = 0; i < str.length(); i++) {
        log.append("" + str.charAt(i));

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (i == str.length() - 1) {
            log.append("\n");
        }
    }
}

public void setLocation(int x, int y) {
    frame.setLocation(x, y);
}

public void setLocationRelativeTo(Component c) {
    frame.setLocationRelativeTo(c);
}

public LoginTerminal() {
    try {

        InputStream is = LoginTerminal.class.getResourceAsStream("/fonts/dungeon.TTF");
        Font font = Font.createFont(Font.TRUETYPE_FONT, is);
        font = font.deriveFont(Font.PLAIN, 10);

        frame.add(field);
        frame.add(log);

        log.setBackground(Color.BLACK);
        log.setForeground(Color.WHITE);
        log.setWrapStyleWord(true);
        log.setLineWrap(true);
        log.setBounds(4, 20 + 4, frame.getWidth() - 8, frame.getHeight() - 50);
        log.setFont(font);
        log.setEditable(false);
        log.setCaretColor(Color.BLACK);

        field.setBackground(Color.BLACK);
        field.setForeground(Color.WHITE);
        field.setBounds(2, frame.getHeight() - 23, frame.getWidth() - 5, 20);
        field.setFont(font);
        field.setCaretColor(Color.BLACK);
        field.addKeyListener(this);
        field.setText("  >  ");

    } catch (FontFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void dumpToLog() {
    log.append(field.getText() + "\n");
    field.setText("  >  ");
}

public void keyPressed(KeyEvent e) {
    int i = e.getKeyCode();

    if(i == KeyEvent.VK_ENTER && field.isFocusOwner()) {
        if(field.getText().equals("  >  HELP") || field.getText().equals("  >  help")) {
            dumpToLog();


        } else {
            dumpToLog();
        }
    }


    if(!field.getText().startsWith("  >  ")) {
        field.setText("  >  ");
    }
}

public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}

}
public class Main {

    public static void main(String[] args) {
        new Login();
    }

}
我的问题是:

public Login() {
    login.slowPrint("Please login to continue...\n"
               + "Type 'help' for more information.\n");
}
当我运行它时,它会按预期工作

而在同一类中(Login.class)

它冻结并等待完成

我想这可能是线索。睡眠(50);在LoginTerminal.class中,由于这是触发键入动画的原因,因此标题为

希望我在这里说清楚。 谢谢大家的帮助

编辑

这就是导致计时器错误的原因

public void timerPrint(String text) {
Timer timer = new Timer(50, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (index < text.length() - 1 && index >= 0) {
            String newChar = Character.toString(text.charAt(index));
            textArea.append(newChar);
            index++;
        } else {
            textArea.setText(null);
            index = 0;
           // You could stop the timer here...
        }
   }
});
timer.start();
}
public void timerPrint(字符串文本){
计时器计时器=新计时器(50,新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
如果(索引=0){
字符串newChar=Character.toString(text.charAt(index));
textArea.append(newChar);
索引++;
}否则{
textArea.setText(空);
指数=0;
//你可以在这里停止计时。。。
}
}
});
timer.start();
}
构造函数计时器(int,new ActionListener(){})未定义

编辑,全班:

package com.finn.frametypes;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.io.InputStream;

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

import com.finn.gui.CustomFrame;
import com.finn.gui.Types;

public class LoginTerminal implements KeyListener {

CustomFrame frame = new CustomFrame(Types.TERMINAL);

JTextArea log = new JTextArea();
public JTextField field = new JTextField();

public void setVisible(boolean bool) {
    frame.setVisible(bool);
}

public void addKeyListener(KeyListener listener) {
    frame.addKeyListener(listener);
}
public void timerPrint(String text) {
Timer timer = new Timer(50, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (index < text.length() - 1 && index >= 0) {
            String newChar = Character.toString(text.charAt(index));
            textArea.append(newChar);
            index++;
        } else {
            textArea.setText(null);
            index = 0;
           // You could stop the timer here...
        }
   }
});
timer.start();
}

public void slowPrint(String str) {
    for(int i = 0; i < str.length(); i++) {
        log.append("" + str.charAt(i));

        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (i == str.length() - 1) {
            log.append("\n");
        }
    }
}

public void setLocation(int x, int y) {
    frame.setLocation(x, y);
}

public void setLocationRelativeTo(Component c) {
    frame.setLocationRelativeTo(c);
}

public LoginTerminal() {
    try {

        InputStream is = LoginTerminal.class.getResourceAsStream("/fonts/dungeon.TTF");
        Font font = Font.createFont(Font.TRUETYPE_FONT, is);
        font = font.deriveFont(Font.PLAIN, 10);

        frame.add(field);
        frame.add(log);

        log.setBackground(Color.BLACK);
        log.setForeground(Color.WHITE);
        log.setWrapStyleWord(true);
        log.setLineWrap(true);
        log.setBounds(4, 20 + 4, frame.getWidth() - 8, frame.getHeight() - 50);
        log.setFont(font);
        log.setEditable(false);
        log.setCaretColor(Color.BLACK);

        field.setBackground(Color.BLACK);
        field.setForeground(Color.WHITE);
        field.setBounds(2, frame.getHeight() - 23, frame.getWidth() - 5, 20);
        field.setFont(font);
        field.setCaretColor(Color.BLACK);
        field.addKeyListener(this);
        field.setText("  >  ");

    } catch (FontFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void dumpToLog() {
    log.append(field.getText() + "\n");
    field.setText("  >  ");
}

public void keyPressed(KeyEvent e) {
    int i = e.getKeyCode();

    if(i == KeyEvent.VK_ENTER && field.isFocusOwner()) {
        if(field.getText().equals("  >  HELP") || field.getText().equals("  >  help")) {
            dumpToLog();


        } else {
            dumpToLog();
        }
    }


    if(!field.getText().startsWith("  >  ")) {
        field.setText("  >  ");
    }
}

public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}

}
package com.finn.frametypes;
导入java.awt.Color;
导入java.awt.Component;
导入java.awt.Font;
导入java.awt.FontFormatException;
导入java.awt.event.KeyEvent;
导入java.awt.event.KeyListener;
导入java.awt.event.ActionEvent;
导入java.io.IOException;
导入java.io.InputStream;
导入javax.swing.JTextArea;
导入javax.swing.JTextField;
导入javax.swing.Timer;
导入com.finn.gui.CustomFrame;
导入com.finn.gui.Types;
公共类LoginTerminal实现了KeyListener{
CustomFrame=新的CustomFrame(Types.TERMINAL);
JTextArea log=新的JTextArea();
public JTextField=new JTextField();
公共无效集合可见(布尔布尔布尔值){
frame.setVisible(bool);
}
public void addKeyListener(KeyListener侦听器){
frame.addKeyListener(listener);
}
公共无效timerPrint(字符串文本){
计时器计时器=新计时器(50,新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
如果(索引=0){
字符串newChar=Character.toString(text.charAt(index));
textArea.append(newChar);
索引++;
}否则{
textArea.setText(空);
指数=0;
//你可以在这里停止计时。。。
}
}
});
timer.start();
}
公共void slowPrint(字符串str){
对于(int i=0;i”);
}捕获(FontFormat异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
公共无效转储日志(){
log.append(field.getText()+“\n”);
字段。setText(“>”);
}
按下公共无效键(按键事件e){
int i=e.getKeyCode();
如果(i==KeyEvent.VK\u输入&&field.isFocusOwner()){
if(field.getText().equals(“>HELP”)| | field.getText().equals(“>HELP”)){
dumpToLog();
}否则{
dumpToLog();
}
}
如果(!field.getText().startsWith(“>”)){
字段。setText(“>”);
}
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
回答

如果将来有人读到这篇文章并希望在Java中使用slowprinting,请使用以下命令:

int index;

public void timerPrint(final String text) {
    Timer timer = new Timer(50, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (index < text.length() - 1 && index >= 0) {
                String newChar = Character.toString(text.charAt(index));
                textarea.append(newChar);
                index++;
            } else {
                index = 0;
                ((Timer)e.getSource()).stop();
            }
       }
    });
    timer.start();
}
int索引;
public void timerPrint(最终字符串文本){
计时器计时器=新计时器(50,新ActionListener(){
已执行的公共无效操作(操作事件e){
如果(索引=0){
字符串newChar=Character.toString(text.charAt(index));
textarea.append(newChar);
索引++;
}否则{
指数=0;
((计时器)e.getSource()).stop();
}
}
});
timer.start();
}

Swing是一个单线程框架,也就是说,任何阻止事件调度线程的操作都会阻止UI更新或程序响应新线程

有关更多详细信息,请参阅

您不应该执行任何阻塞(
Thread.sleep
)或长时间阻塞