处理发生时动态刷新JTextArea?

我正在尝试创建一个非常简单的Swing UI,通过JTextArea将信息记录到屏幕上,因为处理在后台进行。 当用户点击按钮时,我希望每次调用:

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

立即显示在用户界面中。

目前,在单击按钮后处理完成之前,JTextArea不会显示所有日志信息。 我怎样才能让它动态刷新?

我的应用程序遇到了同样的问题。 我有一个“运行”按钮我的应用程序执行了一些操作并将结果输出到JTextArea。 我不得不从Thread调用该方法。 这就是我做的。

我有几个可以执行操作的单选按钮,然后一个“运行”按钮来执行该特定操作。 我有一个名为Validate的动作。 因此,当我检查单选按钮并单击“运行”按钮时,它会调用方法validate()。 所以我首先将此方法放入实现Runnable的内部类中

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

然后,我在“运行”按钮的ActionListener中调用此线程,如此

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

瞧! 输出现在发送到JTextArea。

现在,您将注意到JTextArea不会向下滚动文本。 所以你需要设置插入位置

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

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

尝试这个:

 jTextArea.update(jTextArea.getGraphics()); 

正如其他人所说,这需要multithreading。 看看Swing中的Concurrency 。

一种解决方案是使用SwingWorker实现处理。 doInBackground方法将实现处理,您将使用要作为参数附加的String调用publish方法。 然后,您的SwingWorker将覆盖进程方法以获取String参数并将其附加到文本区域。

我很抱歉回复4年前发布的这个问题,但我有另一种解决方案对我有用。 我只是使用指针来更新JTextArea

 //JScrollPane variable pane initialized with JTextArea area //We will update area with new text JTextArea temp = (JTextArea) pane.getViewPort().getView(); //new text to add JTextArea c = new JTextArea(); c.append("text \n)"; //update through pointers temp = c; pane.validate(); 

你需要multithreading才能做到这一点。 准备冒险了吗?

如果它是multithreading的,你需要试试这个! http://www.devarticles.com/c/a/Java/Multithreading-in-Java/