I'm working on a simple 2 way chat program that I need to convert to a GUI so I can use with friends. The problem I'm running into is that I using a TextArea as the basis of the chat session and in order to append things to it it needs to be a string. I need to convert the stream coming from my friend who has the client into text that will show up on the servers side.
Here's the full code(Incomplete):
The part i'm having trouble with is:
Any help or comments would be greatly appreciated!!!
Not sure what your problem is, since you never say what it is. A couple of things:
- If you have a Stream coming from your friend into this application that you have an InputStream, not an OutputStream. An OutputStream is what you would write to to send data to the friend.
- The correct way to get data from an InputStream into a String (so it can be added to a TextArea) would be t wrap it into a Reader (such as a BufferedReader), then read the contents of the stream using one of the Reader methods which returns a String.
It seems to me in your second snippet of code you do this - assuming br is a BufferedReader. But that snippet is out of context so it is hard to say. So if you have problems then you need to tell us what those problems are.
Oh, I see, the second code snippet actually comes from the first code snippet's actionPerformed method. More comments:
- Never ever ever ever ever put an infinite, or even a long loop inside an actionPerformed method. This blocks the GUI thread making it impossible for the user to interact with the user interface.
- You need to always be listening to the input stream for input, and you need to do it while the GUI code is responsive to the user. This means you need another Thread to do the InputStream reading. A good tool to use for this is a SwingWorker (and read this tutorial).
- The work of getting the text to send to the friend should be separate from the work to get data from the friend. Since this will tend to be short it can be done in the actionPerformed method - but no loop! just do a single 'get text from text field, send it to output' in the actionPerformed method. If the user wants to send multiple things to their friend they will press the button multiple times.
Joined: Jan 05, 2013
Sorry about providing no context with the second section I wrote it right before I went to bed so I wouldn't forget to do it.
Thanks for the help but I've actually taken up the program with a friend and we've completely redone the program in a much much more simpler way, but thanks a lot for the tips I'll make sure to remember them for the future.