3

我有以下课程:

  • 主服务器
  • TCP服务器
  • UDP服务器

我从 MainServer 类创建 TCPServer 和 UDPServer 类的新实例(开始),我的 GUI 在其中初始化。在这个 GUI 中,我有一个textArea,TCP 或 UDP 类需要更新它以显示日志信息(错误、状态等)。我做了一些搜索,我知道我可能需要在 MainServer 中使用 EDT,但不知道如何从 TCPServer 或 UDPServer 访问 MainServer 类中的这个对象。现在我只能打印到控制台,这是不可取的。如何从 TCPServer 访问 MainServer.printlog?或 Mainserver.textArea 对象?如果我从 TCPServer 或 UDPServer 创建一个新的 MainServer 实例,这似乎不起作用。

这是我在 MainServer 类中的函数:

public void printLog (final String log, final int level) {

    SwingUtilities.invokeLater(
    new Runnable() 
    {
        public void run() 
        {
        if (level == 1) 
            textArea.append("INFO\t" + log);
        if (level == 2)
            textArea.append("WARN\t" + log);
        if (level == 3)
            textArea.append("ERROR\t" + log);
        }
    }
    );
}

编辑:我试图创建一个新的实例MainServer并访问printLog,但我得到:

线程“AWT-EventQueue-0”中的异常 java.lang.NullPointerException
    在 MultithreadedBarcodeReader.MultithreadedBarcodeReaderServer$2.run(
        多线程BarcodeReaderServer.java:68)
    在 java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    在 java.awt.EventQueue.dispatchEventImpl(EventQueue.java:682)
    在 java.awt.EventQueue.access$000(EventQueue.java:85)
    在 java.awt.EventQueue$1.run(EventQueue.java:643)
    在 java.awt.EventQueue$1.run(EventQueue.java:641)
4

2 回答 2

2

出现NullPointerException在第 68 行嵌套在 中的匿名类中MultithreadedBarcodeReaderServer,大概是Runnable被引用的。有人可能会猜测, as没有textArea被取消引用并且是原始的。您需要在调试器中的该行附近中断才能确定。还要验证您的 GUI 组件是否事件调度线程上构建和操作。nullloglevel

于 2012-09-03T01:07:39.060 回答
1

考虑使用一个单独的日志框架,或者至少一个带有静态方法的单独的日志类(或者一个带有静态方法的日志工厂)。对于您的应用程序,它们是否登录到控制台、a、... 都无关紧要JTextArea,而且您当然不想MainServer仅出于记录目的而传递实例。

Then your application can simply 'log' those messages, and if you want to display those on a certain JTextArea, you can simply add a handler which does exactly this. This handler can then be created in the same location as where you create the actual JTextArea, and of course can append the log messages on the Event Dispatch Thread.

Other advantages of using a decent logging framework are that you can activate the logging on a per-class basis, configure the logging level on a per-class basis, ... and all that without making any changes to your code. So this allows to gather "debug-information" from a deployed application (perhaps even information you do not want to appear in the JTextArea but you want to know to diagnostic a problem).

于 2012-09-03T07:19:09.480 回答