java - 如何强制 JTextArea 可编辑、可点击并立即刷新输出?

标签 java swing jtextarea thread-sleep

我有两个类。主要类:

public class TestJTA {


        public static JTextArea text;

        public static void main(String [] args) {
            Runnable r = new Runnable() {
                public void run() {
                                        createGUI();
                 }

            } ;
    javax.swing.SwingUtilities.invokeLater(r);
        }

    public static  void createGUI() throws IOException {

        JFrame j = new JFrame("C5er");
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ActionListener al = new ActionListener() {
            @SuppressWarnings("deprecation")
            public void actionPerformed (ActionEvent e ) {
                try {
                    PrintToJTA.startPrinting();
              } catch (Exception ex) {}
            }
        }
        ;
        j.setLayout(null);

        text = new JTextArea();
        JScrollPane scroll = new JScrollPane(text);
        scroll.setBounds(280,30,200,100);
        j.add(scroll);


        JButton b = new JButton("Start");
        b.setBounds(100,20,80,30);
        b.addActionListener(al);
        j.add(b);


        j.setSize(600,250);
        j.setVisible(true);
        j.setLocationRelativeTo(null);
        j.getContentPane().setBackground(Color.white);
    }

}

第二类是:

public class PrintToJTA {
public static void startPrinting () throws InterruptedException {
    for (int i = 0; i < 10 ; i++) {
        TestJTA.text.append("hello\n");
Thread.sleep(300);
    }
}
}

当我单击开始时,文本区域卡住...并且变得不可单击...并且仅在一段时间后我才得到输出。 如何使 JTextArea 始终可点击、可编辑并立即刷新输出?我需要它在 Thread.sleep 等待期间可点击

最佳答案

好的,正是时候学习SwingTimer .

Thread#sleep() 通常与命令行一起使用,但对于 GUI,强烈建议使用 SwingTimers:

public class PrintToJTA {
private final int delay = 20;
private int counter;
private javax.swing.Timer timer;
private JTextArea area;
{timer = new javax.swing.Timer(delay,getTimerAction());}

public void startPrinting (JTextArea textArea) throws InterruptedException {
       //....
       area = textArea;
       timer.start();
    }
private ActionListener getTimerAction(){
  return new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
        if(++counter >= 10)
           timer.stop();
        area.appent("Hello\n");

     }
};

}

就这样调用它

//....
new PrintToJTA().startPrinting(text );
//...

注意:我没有编译此代码。

关于java - 如何强制 JTextArea 可编辑、可点击并立即刷新输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19411836/

相关文章:

java - 如何为 jTextArea 中的选定文本设置字体颜色?

java - 制作一个可以从另一个类打印的文本区域

java - 正则表达式验证空字母或仅字母

java - 如何编写一个通用的 java 客户端来处理 1-way 和 2-way ssl?

java - mule-domain-config 中的 org.xml.sax.SAXParseException : Failed to read schema document mule-mongo. xsd

java - 微服务中的事务

java - 当 JFrame 中有背景图像时将 JButtons 移至左侧

java - 试图在 JScrollPanel Java 的 JTable 中获取二维数组

java - 如何递归删除JTree中的所有节点?

java - Swing 文本组件无法从剪贴板粘贴大文本数据 : java. io.IOException: Owner failed to convert data