从不同地方向 swing JTextArea 发送消息

发布于 2024-10-04 19:22:28 字数 284 浏览 4 评论 0原文

我有一个 JTextArea 在我的主应用程序窗口中始终可见(如果您愿意,可以是一个日志),我想用它来显示系统中正在进行的活动(就像您使用 System.out.println( 执行的模拟调试输出一样) )在 if 条件或其他情况下)

我的意思是用户所做的高级操作(例如“成功加载文件”或“写入磁盘”,“已完成”等)

事情是这样的消息可以在我的系统中的任何地方主要在另一个包中生成其中的类处理数据和计算,并且它们不知道 GUI。

也许将消息保存到临时文件中,并且文本区域“监视”该文件的更改,这如何完成?

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)

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

只有一腔孤勇 2024-10-11 19:22:28

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

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

然后将其传递给您的非 GUI 组件,这样它们就不会与特定的实现绑定:

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

}

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

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 等)并编写一个“写入”文本组件的附加程序。

The simplest way is to define a logger interface:

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

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

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.

辞取 2024-10-11 19:22:28

设计可能相当复杂。也许您可以在 TextArea 所在的类中拥有像 updateText() 这样的公共访问方法。然后,您创建一种“资源”或“共享”类(只是一个普通类),它们将在 main() 运行时一起初始化。创建包含 TextArea 的类时,一个实例将被放置到“共享”类中(此共享类应该是单例),因此所有其他类都调用此“共享”类(可能是像 updateTextArea() 这样的方法)它要做的就是通过该实例调用包含 TextArea 的类,并调用 TextArea 来更新文本。

The design can be rather complicated. Maybe you can have a public access method like updateText() in the class where your TextArea would be. Then you create a kind of 'resource' or 'shared' class (just a plain class) that would be initialized together when your main() runs. When the class containing your TextArea is created, an instance would be placed into the 'shared' class (this shared class should be a singleton) and so all the other classes call this 'shared' class (maybe a method like updateTextArea()) and what it would do is call the class containing the TextArea via that instance and call the TextArea to update text.

撑一把青伞 2024-10-11 19:22:28

消息控制台可能就是您正在寻找的。

Java 还有一个“Logger”API。

The Message Console might be what you are looking for.

Java also has a "Logger" API.

作业与我同在 2024-10-11 19:22:28

您可以使用 EventBus 将 GUI 与应用程序的其他部分分离。 (我的博客还有另一个介绍)。您可以执行以下操作:

public class LogArea extends JTextArea {
    public static final String LOG_TOPIC = "logarea_topic";

    public LogArea() {
        super();
        // Read in the annotations, register self as a listener to the topic
        AnnotationProcessor.process(this);
    }

    @EventTopicSubscriber(topic=LOG_TOPIC)
    public void logEvent(String topic, String text) {
        append(text + "\n");
    }

}

public class DomainClass {

    public void foo() {
        // Send out a notification throughout the system to whichever components
        // are registered to handle this topic.
        EventBus.publish(LogArea.LOG_TOPIC, "some text you want to appear in the log area");
    }

}

在真实的系统中,您可能希望将主题声明移动到另一个类,以便可以使用它而无需绑定到特定的实现。例如,您可以有一个仅包含主题的静态字符串常量的 Topics 类。然后,您可以拥有多个类来侦听这些主题并处理消息(例如,您可以拥有一个标准日志记录框架,除了 jtextarea 组件之外,该框架还可以将其写入日志文件)。

You can use EventBus to decouple your GUI from the other parts of your application. (My blog has another introduction). You could do something as follows:

public class LogArea extends JTextArea {
    public static final String LOG_TOPIC = "logarea_topic";

    public LogArea() {
        super();
        // Read in the annotations, register self as a listener to the topic
        AnnotationProcessor.process(this);
    }

    @EventTopicSubscriber(topic=LOG_TOPIC)
    public void logEvent(String topic, String text) {
        append(text + "\n");
    }

}

public class DomainClass {

    public void foo() {
        // Send out a notification throughout the system to whichever components
        // are registered to handle this topic.
        EventBus.publish(LogArea.LOG_TOPIC, "some text you want to appear in the log area");
    }

}

In a real system you'd probably want to move the topic declarations to another class so that one can use it without being tied to a specific implementation. E.g. you could have a Topics class that just contains the static string constants of the topics. Then you can have multiple classes that listen to those topics and process the messages (e.g. you could have a standard logging framework which writes out to a log file in addition to the jtextarea component).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文