Need help with integrating chat into Gui

Hello Guys,
I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class Client
extends JPanel {
public static void main(String[] args) throws IOException {
String name = args[0];
String host = args[1];
int port = Integer.parseInt(args[2]);
final Socket s = new Socket(host, port);
final Client c = new Client(name, s);
JFrame f = new JFrame("Client : " + name);
f.addWindowListener(new WindowAdapter() { 
public void windowClosing(WindowEvent we) { 
c.shutDown();
System.exit(0);
f.setSize(300, 300);
f.setLocation(100, 100);
f.setContentPane(c);
f.setVisible(true);
private String mName;
private JTextArea mOutputArea;
private JTextField mInputField;
private PrintWriter mOut;
public Client(final String name, Socket s)
throws IOException {
mName = name;
createUI();
wireNetwork(s);
wireEvents();
public void shutDown() {
mOut.println("");
mOut.close();
protected void createUI() {
setLayout(new BorderLayout());
mOutputArea = new JTextArea();
mOutputArea.setLineWrap(true);
mOutputArea.setEditable(false);
add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
mInputField = new JTextField(20);
JPanel controls = new JPanel();
controls.add(mInputField);
add(controls, BorderLayout.SOUTH);
mInputField.requestFocus();
protected void wireNetwork(Socket s) throws IOException {
mOut = new PrintWriter(s.getOutputStream(), true);
final String eol = System.getProperty("line.separator");
new Listener(s.getInputStream()) {
public void processLine(String line) {
mOutputArea.append(line + eol);
mOutputArea.setCaretPosition(
mOutputArea.getDocument().getLength());
protected void wireEvents() {
mInputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String line = mInputField.getText();
if (line.length() == 0) return;
mOut.println(mName + " : " + line);
mInputField.setText("");

I think the easiest way to do it would be to cut an paste most of that code into your program. Then all you have to do is change some names so that it uses your textfield and textarea.

Similar Messages

  • Need Help with Simple Chat Program

    Hello Guys,
    I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class Client
    extends JPanel {
    public static void main(String[] args) throws IOException {
    String name = args[0];
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    final Socket s = new Socket(host, port);
    final Client c = new Client(name, s);
    JFrame f = new JFrame("Client : " + name);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    c.shutDown();
    System.exit(0);
    f.setSize(300, 300);
    f.setLocation(100, 100);
    f.setContentPane(c);
    f.setVisible(true);
    private String mName;
    private JTextArea mOutputArea;
    private JTextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new JTextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new JTextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");

    Thanks for ur help!i have moved BufferedReader outside the loop. I dont think i am getting exception as i can c the output once.What i am trying to do is repeat the process which i m getting once.What my method does is first one sends the packet to multicasting group (UDP) and other method receives the packets and prints.

  • Need help with Google Chat

    Hi,
    These questions might be really simple because I think I'm one of the only people in the UK that's never used an IM before.  I thought that as my phone (Palm Pre) could do instant messaging I'd have a go at it.  I already had a google mail account (set up to sync my calendars) so thought it'd be easiest to use google chat.  However, I seem to only be able to chat with people I've invited or who have invited me to to be their firends, but I can't work out how to do this on the phone.
    Yesterday my husband used his phone (HTC desire) to invite me to be his friend on google chat but I couldn't see the invite on my phone.  I had to log into my google account on my PC and accept the invitation before we could chat.  I also can't see how I invite other people via my phone.  I tried logging onto my google account using my phone's browser, but it didn't seem to display the bit where you type the name to invite people.
    My other question is probably even more basic.  If I have friends on MSN or other messenger services can I contat them using my googlechat service on my phone, or do I have to set up an account for each different messaging service.
    Thanks to anyone who can help on this.
    P.S.  Please don't let my husbands phone be better at this than mine or I'll never hear the end of it :-)

    See http://discussions.apple.com/message.jspa?messageID=9245877#9245877

  • Need help with facebook chat and notifications

    Hey, guys.
    Since I update to software version 10.2.1.2102 I havent been able to recieve facebook chat messages on the blackberry hub. Before the update anytime I had my phone conected to a wireless network it automatically recieved facebook messages on the hub. Now, although I can send messages, and recieve messages if that contact happens to be online, once I close the hub the conversation is gone and I do not get any more messages, only the "new messages from *person*" e-mail after some time.
    Also, I do not get notifications about people's birthdays. I get the "Next event in x hours" notification on the lock screen, if I do go into the calendar I see the notification at the top of the page, but it does not ring to warn me of my contacts birthdays.
    Can anyone help me with this two problems? Thank you!
    Solved!
    Go to Solution.

    Start by resetting your Hub. While in the Hub, swipe down diagonally from the top right corner to the center of your screen four times in a row.
    Let us know if that helps you.  
    - If my response has helped you, please click "Options" beside my post and mark it as solved. Clicking the "thumbs up" icon near the bottom of my response would also be appreciated.

  • I need help with Importing songs into Creative organizer please help!

    OK now i have a bunch of music files in my documents that all have MPEG4 with the itunes music symbol next to them. My problem is when i try to add them to my Windows media player nothing happens also when i search for the files in the Creative Import Wizard nothing shows up! Do i first need to put all the music i want on my ZVM im Windows Media Player first then add it's or is it something else? do i need to get rid of itunes entirely and just have the music files in my documents? Im really really confused please help!!!!!! Also No tracks show up when i try to add them to Windows Media Player or Creative MediaSource5 even though when i know i put them there
    P.S. What do u guys do ( I mean people with Zen Vison M's) Any know of any guides too? that would be great!Message Edited by Chrismic3 on 03-9-200705:54 PM
    Message Edited by Chrismic3 on 03-9-200706:00 PM

    bump

  • Need help with moving files into Itunes and syncing

    Please help.
    I have an external hard drive with my music on it.  I created a new playlist in Itunes and did a drag and drop from my external hard drive into my newly created playlist. 
    Now that I go back and play the items I brought over, I get an error that says "original files not found" and it won't play and therefore does not seem to be syncing to the Ipod to be able to play.
    Can you please give me guidance as to what I can do without recreating all the work I had already done?
    Thanks,
    Michelle

    Is the external drive connected?
    Has the drive letter possibly changed due to being disconnected and reconnected?

  • Need help with threading in Swing GUI !!!

    I've written an app that parses and writes
    files. I'm using a Swing GUI. The app
    could potenially be used to parse hundreds or even
    thousands of files. I've included a JProgressBar
    to monitor progress. The problem is when I parse
    a large number of files the GUI freezes and only
    updates the values of the progress bar when the
    parsing and writing process is finished.
    I assume I need to start the process in a seperate thread. But, I'm new to threads and I'm not sure
    whether to start the Progressbar code in a seperate
    thread or the parsing code. As a matter of fact I really
    don't have any idea how to go about this.
    I read that Swing requires repaints be done in the
    event dispatch thread. If I start the parsing in a seperate
    thread how do I update the progressbar from the other
    thread? I'm a thread neophyte.
    I need a cigarette.

    In other words do this:
    Inside event Thread:
    handle button action
    start thread
    return from action listener
    Inside worker Thread:
    lock interface
    loop
    perform action
    update progress bar
    unlock interface
    return from worker ThreadDoesn't updating the progress bar (and locking/unlocking the interface components) from within the worker thread violate the rule that you shouldn't mess with Swing components outside the event thread? (Do I have that rule right?)
    In any case, is there any way to just post some kind of event to the progress bar to update it from within the worker thread, thereby insuring that the GUI progress bar update is being invoked from the event thread? This would also obviate the need to use a timer to poll for an update, which I think is a waste especially when the monitored progress is at a variable rate, (or for number crunching, is executing on different speed machines).
    Also, doesn't using invokeLater() or invokeAndWait() still block the event dispatching thread? I don't understand how having a chunk of code started in the event thread doesn't block the event thread unless the code's executed in a "sub-thread", which would then make it not in the event thread.
    I'm also looking to have a progress bar updated to monitor a worker thread, but also want to include a "Stop" button, etc. and need the event queue not to be blocked.
    The last thing I can think of is to implement some kind of original event-listener class that listens to events that I define, then register it with the system event queue somehow, then have the worker thread post events to this listener which then calls setValue() in the progress bar to insure that the bar is updated from the event queue and when I want it to be updated. I don't know yet if it's possible to create and register these kinds of classes (I'm guessing it is).
    Thanks,
    Derek

  • I need help with random number in GUI

    hello
    i have home work about the random number with gui. and i hope that you can help me doin this application. and thank you very much
    Q1)
    Write an application that generates random numbers. The application consists of one JFrame,
    with two text fields (see the figures) and a button. When the user clicks on the button, the
    program should generate a random number between the minimum and the maximum numbers
    entered in the text fields. The font of the number should be in red, size 100, bold and italic.
    Moreover, if the user clicks on the generated number (or around it), the color of the background
    should be changed to another random color. The possible colors are red, green blue , black ,cyan
    and gray.
    Notes:
    �The JFrame size is 40 by 200
    �The text fields size is 10
    this is a sample how should the programe look like.
    http://img235.imageshack.us/img235/9680/outputgo3.jpg
    Message was edited by:
    jave_cool

    see java.util.Random

  • Need help with inserting element into a grid

    Hi,
    I'm trying to add an element in a 11x11 grid, but the program stop and give me 2 error (identified in the code) and I have no idea on what is wrong with those line. If anyone have any idea, suggestion or an other way to do this, I could use some help.
    Thx
              for (int i = 0; i != NUMBER; ++i) {
                      int row = 2 + (int)(Math.random() * 10);
                   int col = 2 + (int)(Math.random() * 10);
                   int nb = 0 + (int)(Math.random() * 2);
                   boolean horizontal = true;
                   if (nb == 1)
                        horizontal = false;
                   if (horizontal) {
                        if (row <= element.getDimension()) {  // error at this line
                             for (int j = 0; j != element[i].getDimension(); j++) {
                                  grid[row + j][col]     = "X";
                        else {
                             for (int j = 0; j != element[i].getDimension(); j++) {
                                  grid[row - j][col]     = "X";
                   if (! horizontal) {
                        if (col <= element[i].getDimension()) { // error at this line
                             for (int j = 0; j != element[i].getDimension(); j++) {
                                  grid[row][col + j]     = "X";
                        else {
                             for (int j = 0; j != element[i].getDimension(); j++) {
                                  grid[row][col - j]     = "X";

    My error is : Exception in thread "main" java.lang.NullPointerException
    at Grid.<init><Grid.java:67>
    at PrincTp1.main<PrincTp1.java:24>
    That's my class element
    public class Element {
    // Attributs
         private int dimension;
         private boolean horizontal;
         private String name;
         private int row;
         private int col;
    // Constructor
         public Element(int dimension_, String name_) {
              dimension = dimension_;
              name = name_;
         public Element() {
    // getter/setter
         public void setDimension(int dimension_) {
              dimension = dimension_;
         public int getDimension() {
              return dimension;
         public void setHorizontal(boolean horizontal_) {
              horizontal = horizontal_;
         public boolean getHorizontal() {
              return horizontal;
         public void setNom(String name_) {
              name = name_;
         public String getName() {
              return name;
         public void setLigne(int row_) {
              row = row_;
         public int getRow() {
              return row;
         public void setCol(int col_) {
              col = col_;
         public int getCol() {
              return col;
         }

  • Need help adding live chat into Adobe Muse

    Has anyone successfully added a live chat feature into Adobe Muse?
    We're in final design stages of creating new site and would like to use a live chat program (Olark, Live Person, etc) -- have received the html embed, attempted to add the html into a page unsuccessfully.   We've added code in other pages. 
    Thanks.

    Most of those services would have given you a guide on where to place the code. The code mostly would be embedded in the head section. To do that in Muse, right click anywhere on the board-select page properties-metadata-head. Then paste the code there. Publish your site and you would see the chat widget on your site.

  • Need help with integrating a dreamweaver file and an edge file

    Alright so I have been trying to do this for far to long so I am asking for some help this is for a web design class.
    I am trying to either import a edge composition to a dreamweaver file or use the publish file from the edge file to make a completed website by adding a css navigation bar from an external css file. I want to have the css menu to the left of the logo. I have tried this numerous times but either the menu doesn't show up and is either behind the edge stage or its not there at all. When I tried it from a fresh html page and imported it from an oam file the images from the stage never showed up and I am unsure how to fix that.
                                                                ^right there.
    Here are the files
    Dropbox - Archive.zip
    Thanks for the help.

    I found the z-index for the edge animate code and it was set to 0 and i set the menu div to 40 but nothing happened and it didn't show up. This where i set the menu to a higher value and I'm not sure if this is correct, I also tried it in the css file but that also didn't work.
                <div id='cssmenu' style="z-index:40;">
      <ul>
       <li><a href='index.html'>Sell Cards</a>
          <ul>
             <li><a href='#'>Pricing Guide</a></li>
             <li><a href='buyList.html'>Buy List</a></li>
          </ul>
       </li>
       <li><a href='#'>Sealed Product</a>
          <ul>
             <li><a href='Promotional Items'>List of Sets</a></li>
             <li><a href='#'>Promotional Items</a></li>
          </ul>
       </li>
       <li><a href='#'>Other Games</a></li>
       <li><a href='supplies.html'>Gaming Supplies</a></li>
    </ul>
    </div>

  • Need help with entering data into a table.

    I just created a table, but I can't enter information.  I don't want the data linked to a datasource.  I just want it to save to the form like all of the other fields.

    Even when I create a simple table, no ability to enter information.  Please help.  I know this must be a simple answer, but surprised that there is no response.

  • Need help!!!! GUI problems with netbeans

    i have a problem with the interface i created using netbeans.
    i created a JFrame, inside it a JDesktopPane, and inside that 3 JInternalFrames. the problem is in one of the JinternalFrames, i have 4 radio buttons which i forgot to add to a buttongroup and whenever i try to do that, the GUI doesn't work anymore. The bigger problem is that if i undo the changes, the thing still doesn't work and i have to copy my backup project folder over the one i work on to get an output.
    i tried to edit the source code to add the 4 buttons to a button group but netbeans won't let me since i created the buttons thru it not by writing it myself
    please i really need help with this and i hope its a stupid thing i'm just overlooking.
    If u need the code, i will gladly post it.
    thanks in advance

    if you're not using a netbeans-specific layout manager, copy the working code
    into notepad, make the changes, then compile and run from the command prompt.
    if all works OK, dump netbeans

  • I need help with color pallette in iPhoto 11. I have created a book and would like to use a different color background than those given in "background." I have found the color palettes but can't seem to incorporate them into my backgrounds palette.

    I need help with color pallette in iPhoto 11. I have created a book and would like to use a different color background than those given in "background." I have found the color palettes but can't seem to incorporate them into my backgrounds palette.

    That is not a feature of iPhoto - suggest to Apple - iPhoto Menu ==> provide iPhoto feedback.
    Additionally I have no idea what you are saying here
    I have found the color palettes but can't seem to incorporate them into my backgrounds palette.
    And it always helps for you to dientify the version of iPhoto that you are using
    LN

  • Need help with log4j logging tool (org.apache.log4j.*) to log into database

    Hi,
    I need help with log4j logging tool (org.apache.log4j.*) to log into database using JDBCAppender. Have look at my logger code and corresponding log4j.properties file stated below. I'm running this program using Eclipse IDE and it's giving me the following error (highlighted in red) at the end:
    log4j: Parsing for [root] with value=[debug, stdout, Roll, CRSDBAPPENDER].
    log4j: Level token is [debug].
    log4j: Category root set to DEBUG
    log4j: Parsing appender named "stdout".
    log4j: Parsing layout options for "stdout".
    log4j: Setting property [conversionPattern] to [%x %d{HH:mm:ss,SSS} %5p [%t] (%c:%-4L %M) - %m%n].
    log4j: End of parsing for "stdout".
    log4j: Parsed "stdout" options.
    log4j: Parsing appender named "Roll".
    log4j: Parsing layout options for "Roll".
    log4j: Setting property [conversionPattern] to [%x %d{yyyy.MM.dd HH:mm:ss,SSS} %5p [%t] (%c:%-4L %M) - %m%n].
    log4j: End of parsing for "Roll".
    log4j: Setting property [file] to [HelloWorld.log].
    log4j: Setting property [maxBackupIndex] to [10].
    log4j: Setting property [maxFileSize] to [20KB].
    log4j: setFile called: HelloWorld.log, true
    log4j: setFile ended
    log4j: Parsed "Roll" options.
    log4j: Parsing appender named "CRSDBAPPENDER".
    {color:#ff0000}
    Can't find class HelloWorld{color}
    import org.apache.log4j.*;
    public class HelloWorld {
    static Logger log = Logger.getLogger(HelloWorld.class.getName());
    public static void main(String[] args) {
    try{
    // Now, try a few logging methods
    MDC.put("myComputerName", "Ravinder");
    MDC.put("crsServerName", "ARNDEV01");
    log.debug("Start of main()");
    log.info("Just testing a log message with priority set to INFO");
    log.warn("Just testing a log message with priority set to WARN");
    log.error("Just testing a log message with priority set to ERROR");
    log.fatal("Just testing a log message with priority set to FATAL");
    catch(Exception e){
    e.printStackTrace();
    ------------------------- log4j.properties file ------------------------------
    #### Use three appenders - log to console, file and database
    log4j.rootCategory=debug, stdout, Roll, CRSDBAPPENDER
    log4j.debug=true
    # Print only messages of priority WARN or higher for your category
    # log4j.category.your.category.name=WARN
    # Specifically inherit the priority level
    # log4j.category.your.category.name=INHERITED
    #### stdout - First appender writes to console
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%x %d{HH:mm:ss,SSS} %5p [%t] (%c:%-4L %M) - %m%n
    #### Roll - Second appender writes to a file
    log4j.appender.Roll=org.apache.log4j.RollingFileAppender
    ##log4j.appender.Roll.File=${InstanceName}.log
    log4j.appender.Roll.File=HelloWorld.log
    log4j.appender.Roll.MaxFileSize=20KB
    log4j.appender.Roll.MaxBackupIndex=10
    log4j.appender.Roll.layout=org.apache.log4j.PatternLayout
    log4j.appender.Roll.layout.ConversionPattern=%x %d{yyyy.MM.dd HH:mm:ss,SSS} %5p [%t] (%c:%-4L %M) - %m%n
    #### CRSDBAPPENDER - third appender writes to the database
    log4j.appender.CRSDBAPPENDER=org.apache.log4j.jdbc.JDBCAppender
    log4j.appender.CRSDBAPPENDER.Driver=net.sourceforge.jtds.jdbc.Driver
    log4j.appender.CRSDBAPPENDER.URL=jdbc:jtds:sqlserver:/arncorp15:1433;DatabaseName=LOG
    log4j.appender.CRSDBAPPENDER.USER=sa
    log4j.appender.CRSDBAPPENDER.PASSWORD=p8ss3doff
    log4j.appender.CRSDBAPPENDER.layout=org.apache.log4j.PatternLayout
    log4j.appender.CRSDBAPPENDER.sql=INSERT INTO LOG (computername, crsservername, logtime, loglevel, threadname, filename, linenumber, logtext) VALUES ('%X{myComputerName}', '%X{crsServerName}', '%d{dd MMM yyyy HH:mm:ss,SSS}', '%p', '%t', '%F', '%L', '%m')
    #log4j.appender.CRSDBAPPENDER.sql=INSERT INTO LOG(COMPUTERNAME,CRSSERVERNAME,LOGTIME,LOGLEVEL,THREADNAME,FILENAME,LINENUMBER,LOGTEXT) select host_name(),'${CRSServerName}${InstanceName}','%d','%5p','%t','%F','%L','%m%n'
    #log4j.appender.CRSDBAPPENDER.sql=INSERT INTO LOG (computername, crsservername, logtime, loglevel, threadname, filename, linenumber, logtext) VALUES ("%X{myComputerName}", "%X{crsServerName}", "%d{dd MMM yyyy HH:mm:ss,SSS}", "%p", "%t", "%F", "%L", "%m")
    ------------------------------- end of log4j.properties file ------------------------------
    Here is the directory structure of my program. My log4j.properties file and HelloWorld.class file are residing in folder HelloWorld\bin.
    HelloWorld\bin
    HelloWorld\lib
    HelloWorld\src
    Please note - The same program works fine for console and file appender when I comment the database appender part in my properties file.
    Thanks
    Ravinder

    try this :
    log4j.appender.PROJECT.Append=false

Maybe you are looking for

  • Few questions about recovery on P100-400

    Good evening all, I have a few questions about recovering my laptop... So, I was thinking if the only way to clean my entire disk is to use the Recovery DVD? I ask this because I think that the computer becomes too "heavy" with all the applications i

  • Help! my nokia X3-02 just restart and now it have ...

    I was in the web and it just restart after a blink and that has happen to me a lot of times but this time when it restarted the menu now is like the old nokia menu and i try to update my software but i cant and a window say "error -2146435037" I try

  • Itunes doesn't open when ipod connects to pc

    Itunes won't open automatically when I connect to my pc. I have to to click on the itunes icon. I have the box checked marked to open automatically under options.

  • Kdegraphics-3.2.2 needs a patch to compile with gcc-3.4

    Hi, I've tried to compile kdegraphics-3.2.2 with gcc-3.4 without succes, even after changing things in the PKGBUILD file. Just before I gave up I found this patch :-) Patch can be found here: http://bugs.gentoo.org/show_bug.cgi?id=48596 I've download

  • Co product indicator

    Dear all, I have a material xxxx as a co product... In CS03,THis material is having 3 comonents .THe line item numbers are 0010,0020,0030. But when i create prod order for this material xxxx, in the production order BOM another line item 0000 is appe