从不同的地方向swing JTextArea发送消息 [英] Sending messages to a swing JTextArea from different places

查看:198
本文介绍了从不同的地方向swing JTextArea发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主应用程序窗口中总是可以看到JTextArea(如果你愿意,可以使用日志),我想用它来显示系统中正在进行的活动(比如你用System.out做的模拟调试输出) .println()in if conditions or whatever)

I have a JTextArea always visible in my main app window (a Log if you like), and I want to use it to display activity going on in the system (like mock-debug output you'd do with System.out.println() in if conditions or whatever)

我的意思是用户做的高级事情,(比如成功加载文件或写入磁盘,完成等等

I mean high level things the user does, (like "successfully loaded file " or " written to disk", " completed" etc)

事情是这样的消息可以在我的系统中的任何地方生成,主要是在另一个包中处理数据和计算的包中,并且他们没有意识到GUI。

Thing is such messages can be generated anywhere in my system mainly in another package the classes of which deal with the data and computation, and they're unaware of the GUI.

也许将消息保存到临时文件中并且textarea监视该文件的更改,如何做到这一点?

Maybe save the messages to a temp file and the textarea "monitors" that file for changes, how can this be done?

推荐答案

最简单的方法是定义记录器接口:

The simplest way is to define a logger interface:

package com.example.logging;
public interface ActivityLogger {
    void logAction(String message);
}

然后将其传递给非GUI组件,这样它们就不会被束缚具体实现:

Then pass it to your non-GUI components so they don't get tied to a specific implementation:

public class FileLoader {

    private ActivityLogger logger;
    public FileLoader(ActivityLogger logger){
        this.logger = logger;
    }

    public void loadFile(){
        // load stuff from file
        logger.logAction("File loaded successfully");
    }

}

现在,制作一个写入的实现文本组件很简单:

Now, making an implementation that writes to a text component is simple:

public class TextComponentLogger implements ActivityLogger{
    private final JTextComponent target;
    public TextComponentLogger(JTextComponent target) {
        this.target = target;
    }

    public void logAction(final String message){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                target.setText(String.format("%s%s%n", 
                                             target.getText(),
                                             message));
            }
        });
    }
}
// Usage:
JTextArea logView = new JTextArea();
TextComponentLogger logger = new TextComponentLogger(logView);
FileLoader fileLoader = new FileLoader(logger);
fileLoader.loadFile();

您当然也可以使用标准的日志记录框架(java.util.logging,slf4j,log4j,等)并写一个写到文本组件的appender。

You can of course also use a standard logging framework (java.util.logging, slf4j, log4j, etc) and write an appender that "writes" to a text component.

这篇关于从不同的地方向swing JTextArea发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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