在处理发生时动态刷新JTextArea吗? [英] Dynamically refresh JTextArea as processing occurs?

查看:49
本文介绍了在处理发生时动态刷新JTextArea吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个非常简单的Swing UI,以在后台进行处理时通过JTextArea将信息记录到屏幕上.当用户单击按钮时,我希望每个呼叫都可以:

I am trying to create a very simple Swing UI that logs information onto the screen via a JTextArea as processing occurs in the background. When the user clicks a button, I want each call to:

textArea.append(someString + "\n");

立即显示在用户界面中.

to immediately show up in the UI.

目前,在单击按钮后,直到处理完成,JTextArea不会显示所有日志信息.如何获得动态刷新?

At the moment, the JTextArea does not show all log information until the processing has completed after clicking the button. How can I get it to refresh dynamically?

推荐答案

我的应用程序遇到了同样的问题.我的应用程序有一个运行"按钮,它执行一些操作并将结果输出到JTextArea.我不得不从线程中调用该方法.这就是我所做的.

I ran into the same issue with my application. I had a "Run" button my application that performed some actions and outputted the results to a JTextArea. I had to call the method from a Thread. Here is what I did.

我有几个可以完成的动作单选按钮,然后有一个运行"按钮可以执行该特定动作.我有一个称为验证的操作.因此,当我检查该单选按钮并单击运行"按钮时,它将调用方法validate().因此,我首先将此方法放入实现Runnable的内部类

I have several radio buttons of actions that can be done, and then one "Run" button to execute that particular action. I have an action called Validate. So when I check that radio button and click the "Run" button, it calls the method validate(). So I first placed this method into an inner class that implemented Runnable

class ValidateThread implements Runnable {
    public void run() {
        validate();
    }
}

然后我像这样在运行"按钮的ActionListener中调用此线程

I then called this thread in the ActionListener of the "Run" button as so

runButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
        // Some code checked on some radio buttons
        if(radioButton.isSelected()) {
            if(radioButton.getText().equals("VALIDATE")) {
               Runnable runnable = new ValidateThread();
               Thread thread = new Thread(runnable);
               thread.start();
            }
        }
    }

});

Voila!现在将输出发送到JTextArea.

Voila! The output is now sent to the JTextArea.

现在,您将注意到JTextArea将不会随着文本向下滚动.因此,您需要将插入符号位置设置为

Now, you will notice that the JTextArea will not scroll down with the text. So you need to set the caret position like

textArea.setCaretPosition(textArea.getText().length() - 1);

现在,将数据添加到JTextArea时,它将始终向下滚动.

Now when the data is added to the JTextArea, it will always scroll down.

这篇关于在处理发生时动态刷新JTextArea吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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