我有一个更新JTextArea方法中run()的代码。

但是当run方法执行时,不会执行append()方法。

它显示incomingMessage变量的当前值,但不会附加到JTextArea

public void run()
{

    while (true)
    {
        try
        {
            if(serverSocketMessage==null)
            {
                serverSocketMessage = new ServerSocket(Constants.INCOMING_MESSAGE_PORT);
            }
            System.out.println("Listening to incoming messages");

            ObjectInputStream objectInputSender;
            String incomingMessage = null;

            serverMessage = serverSocketMessage.accept();
            objectInputSender = new ObjectInputStream(serverMessage.getInputStream());
            Object objectMessage = objectInputSender.readObject();
            if (objectMessage instanceof String)
            {
                incomingMessage = objectMessage.toString();
                System.out.println("\nMessage\n"+incomingMessage);
                if(incomingMessage!= null)
                {
                    chatingJTextArea.append(incomingMessage);
                    System.out.println("Not null");
                }

                chatingJTextArea.append("\n");
                chatingJTextArea.append(incomingMessage);



            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }

最佳答案

尝试在EDT中调用append

private void addMessage(final String message) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            chatingJTextArea.append(message);

        }
    });
}

关于java - JTextArea在多线程中不起作用-Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18385969/

10-12 21:42