1

I'm making an instant messaging program with a server and a client. The server and client both send messages through a method in separate projects that look like this:

private void sendMessage(String message){

    try{   
        output.writeObject("CLIENT/SERVER - " + message);
        output.flush();
    showMessage("\nCLIENT/SERVER - " + message);
    }catch(IOException ioException){
        chatWindow.append("\n SYSTEM - Something went wrong!");
    }

}

and this:

private void showMessage(final String m){
    SwingUtilities.invokeLater(
    new Runnable(){
        public void run(){
            chatWindow.append(m);
        }
    }
    );
}

All the messages sent by both the client and the server show up in the same JTextArea. I have two questions. First, how do I make it so that each message from the server and the client show up as a different color?

Also, second question, how do I code this so that everything gets appended at the top of the chatWindow rather than the bottom of the chatWindow? Thanks.

  • For your first question: http://stackoverflow.com/questions/2837848/how-can-i-set-partial-text-color-in-jtextarea For your second question: http://stackoverflow.com/questions/12565358/how-to-insert-or-append-new-line-on-top-of-the-jtextarea-in-java-swing – Vincent van der Weele Jul 18 '13 at 19:33
  • Thanks but how to I append the messages in the chatWindow using a JTextPane? – user2596934 Jul 18 '13 at 20:11
  • Ah yeah, if you switch to `JTextPane` the second link is not of much use any more. Instead, see this question http://stackoverflow.com/questions/4059198/jtextpane-appending-a-new-string – Vincent van der Weele Jul 18 '13 at 20:33
  • My code is now telling me to change my methods to this: private void showMessage(final AttributeSet text){ but now my sendMessage method is telling me to change my showMessage method back to this: private void showMessage(final String string){ which is again giving me my insertString errors. I got the insertString stuff from the last link you gave me. What should I do? Thanks for all of your help. – user2596934 Jul 19 '13 at 15:16

0 Answers0