Solved

What code goes where?

Posted on 2003-11-11
13
335 Views
Last Modified: 2010-08-05
I have some code:

public class MessageClient {    
    /** Creates a new instance of MessageClient */
    public MessageClient() {        
        Socket messageSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;

       
        try {
            messageSocket = new Socket("192.168.0.2",4444);
            out = new PrintWriter(messageSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                                        messageSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: ");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                               + "the connection to host.");
            System.exit(1);
        }

      BufferedReader stdIn = new BufferedReader(
                                   new InputStreamReader(System.in));
      String userInput;
        String ReceivedOutput;
        boolean Continue = true;
       
        try{
        //needs to say while true, if user input send it, continue updating screen
      //while ((userInput = stdIn.readLine()) != null) {
          //out.println(userInput);
          //System.out.println("Message: " + in.readLine());
      //}
        while (Continue == true) {
         if ( stdIn.ready()) {
            if ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
             }
         }
         if ( in.ready()) {
            if ((ReceivedOutput = in.readLine())!= null) {
                System.out.println(ReceivedOutput);
             }            
         }
        }
        out.close();
      in.close();
      stdIn.close();
      messageSocket.close();
        } catch (IOException e) {
            System.err.println("Error reading input");
        }
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {        
        new MessageClient();
    }
   
}

As you can see from the code above, is a small program that i have written that sends data over a socket.  However, i want to create a simple user interface for this code.  It must have a swing JFrame with a button on it and a tesxt area for typing messages.  The button sends the last line (meassage) typed to the server program that i have written, so that it can be seen on other clients like this one.  Also when it receives messages from the server it should show them on the text area.  I suppose it is a simple messenger.  

Anyway, the point is i have no idea where to put the code for the user interface, or how to arrange code within the program.  I can write the code, but dont know how to organise it properly so that it is nicely layered etc.  It always ends up in a complete mess with things going out of scope, methods called in the wrong place etc.  Help me with some pointers guys!!!


Thanks

Ashley :-)

p.s I am new to programming and have never written a large program!

0
Comment
Question by:ashleycoker
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
13 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 9721507
Declare two methods:

public void sendMessage(String message) {

}

public void receiveMessage(String message) {

}

and work these into your program. You  can vary the implementation based on how you decide to display things.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9721512
Or that could be

public void sendMessage(BufferedWriter out) {

}

public void receiveMessage(BufferedReader in) {

}


0
 
LVL 15

Expert Comment

by:jimmack
ID: 9721531
Following on from CEHJ...

Your GUI (in a seperate class) will need a reference to the MessageClient in order to be able to call the send/receive methods.

You'll also probably want a seperate Thread to call the receive method at frequent intervals and populate the text area with anything it receives.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 35

Expert Comment

by:TimYates
ID: 9721552
import java.awt.*;
import javax.swing.*;
import java.io.* ;
import java.net.* ;
import java.awt.event.*;

public class MessageClient extends JFrame
{
  class MyReader extends Thread
  {
    public boolean running = true ;
    public BufferedReader input = null ;
   
    public void run()
    {
      while( running )
      {
        try
        {
          if( in.ready() )
          {
            messages.append( in.readLine() ) ;
          }
        }
        catch( IOException ex )
        {
          System.err.println( ex.getMessage() ) ;
        }
      }
    }
  }
 
  BorderLayout borderLayout1 = new BorderLayout();
  JPanel jPanel1 = new JPanel();
  JTextField speech = new JTextField();
  FlowLayout flowLayout1 = new FlowLayout();
  JButton sayBtn = new JButton();
  PrintWriter out = null ;
  BufferedReader in = null ;
  Socket messageSocket = null ;
  JScrollPane jScrollPane1 = new JScrollPane();
  JTextArea messages = new JTextArea();
  MyReader reader = null ;
 
  public MessageClient()
  {
    try
    {
      jbInit();
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
  }

  public void connect()
  {
    try
    {
      messageSocket = new Socket( "192.168.0.2", 4444 ) ;
      out = new PrintWriter( messageSocket.getOutputStream(), true ) ;
      in = new BufferedReader( new InputStreamReader( messageSocket.getInputStream() ) ) ;
      reader = new MyReader() ;
      reader.input = in ;
      reader.start() ;
    }
    catch( UnknownHostException e )
    {
      System.err.println( "Don't know about host: " ) ;
      System.exit( 1 ) ;
    }
    catch( IOException e )
    {
      System.err.println( "Couldn't get I/O for the connection to host." ) ;
      System.exit( 1 ) ;
    }
  }
 
  public static void main(String[] args)
  {
    MessageClient messageClient = new MessageClient();
    messageClient.pack();
    messageClient.connect() ;
    messageClient.show();
  }

  private void jbInit() throws Exception
  {
    this.getContentPane().setLayout(borderLayout1);
    speech.setColumns(30);
    jPanel1.setLayout(flowLayout1);
    flowLayout1.setAlignment(FlowLayout.LEFT);
    sayBtn.setText("Say");
    sayBtn.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        sayBtn_actionPerformed(e);
      }
    });
    this.addWindowListener(new java.awt.event.WindowAdapter()
    {
      public void windowClosing(WindowEvent e)
      {
        this_windowClosing(e);
      }
    });
    messages.setText("");
    this.getContentPane().add(jPanel1, BorderLayout.SOUTH);
    jPanel1.add( speech, null);
    jPanel1.add( sayBtn, null);
    this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.getViewport().add( messages, null );
  }

  void sayBtn_actionPerformed(ActionEvent e)
  {
    out.println( speech.getText() ) ;
    speech.setText( "" );
  }

  void this_windowClosing(WindowEvent e)
  {
    try
    {
      reader.running = false ;
      reader.interrupt();
      out.close() ;
      in.close() ;
      messageSocket.close() ;
    }
    catch( IOException ex )
    {
      ex.printStackTrace();
    }
  }
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9721553
At this stage, I'd recommend the simplest possible gui. This would be a JFrame with a JTextField with ActionListener sitting BorderLayout.NORTH and a JTextPane (possibly JEditorPane) sitting BorderLayout.SOUTH. In the ActionListener, you would call the sendMessage function
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9721555
Dang...too slow :-(
0
 
LVL 35

Accepted Solution

by:
TimYates earned 250 total points
ID: 9721593
Actually, this is neater and better :-)

-------------------------

import java.awt.*;
import javax.swing.*;
import java.io.* ;
import java.net.* ;
import java.awt.event.*;

public class MessageClient extends JFrame
{
  class MyReader extends Thread
  {
    public boolean running = true ;
    public BufferedReader input = null ;

    public void run()
    {
      while( running )
      {
        try
        {
          if( in.ready() )
          {
            messages.append( in.readLine() ) ;
          }
        }
        catch( IOException ex )
        {
          System.err.println( ex.getMessage() ) ;
        }
      }
    }
  }

  BorderLayout borderLayout1 = new BorderLayout();
  JPanel jPanel1 = new JPanel();
  JTextField speech = new JTextField();
  FlowLayout flowLayout1 = new FlowLayout();
  JButton sayBtn = new JButton();
  PrintWriter out = null ;
  BufferedReader in = null ;
  Socket messageSocket = null ;
  JScrollPane jScrollPane1 = new JScrollPane();
  JTextArea messages = new JTextArea();
  MyReader reader = null ;

  public MessageClient()
  {
    try
    {
      jbInit();
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
  }

  public void connect()
  {
    try
    {
      messageSocket = new Socket( "192.168.0.2", 4444 ) ;
      out = new PrintWriter( messageSocket.getOutputStream(), true ) ;
      in = new BufferedReader( new InputStreamReader( messageSocket.getInputStream() ) ) ;
      reader = new MyReader() ;
      reader.input = in ;
      reader.start() ;
    }
    catch( UnknownHostException e )
    {
      System.err.println( "Don't know about host: " ) ;
      System.exit( 1 ) ;
    }
    catch( IOException e )
    {
      System.err.println( "Couldn't get I/O for the connection to host." ) ;
      System.exit( 1 ) ;
    }
  }

  public static void main(String[] args)
  {
    MessageClient messageClient = new MessageClient();
    messageClient.pack();
    messageClient.connect() ;
    messageClient.show();
  }

  private void jbInit() throws Exception
  {
    this.getContentPane().setLayout(borderLayout1);
    speech.setColumns(30);
    jPanel1.setLayout(flowLayout1);
    flowLayout1.setAlignment(FlowLayout.LEFT);
    sayBtn.setText("Say");
    sayBtn.addActionListener(new java.awt.event.ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        sayBtn_actionPerformed(e);
      }
    });
    this.addWindowListener(new java.awt.event.WindowAdapter()
    {
      public void windowClosing(WindowEvent e)
      {
        this_windowClosing(e);
      }
    });
    messages.setText("");
    messages.setRows(20);
    this.getContentPane().add(jPanel1, BorderLayout.SOUTH);
    jPanel1.add( speech, null);
    jPanel1.add( sayBtn, null);
    this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.getViewport().add( messages, null );
    speech.requestFocus();
  }

  void sayBtn_actionPerformed(ActionEvent e)
  {
    out.println( speech.getText() ) ;
    speech.setText( "" );
  }

  void this_windowClosing(WindowEvent e)
  {
    if( reader != null )
    {
      reader.running = false ;
      reader.interrupt();
    }
    if( out != null ) out.close() ;
    try{ if( in != null ) in.close() ; } catch( IOException ex ) { ex.printStackTrace(); }
    try{ if( messageSocket != null ) messageSocket.close() ; } catch( IOException ex ) { ex.printStackTrace(); }
    System.exit( 0 ) ;
  }
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9721619
>>I'd recommend the simplest possible gui

and I've found that where a 'send' button exists, it's much easier to hit return if you're already typing, so the button never gets used.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9721626
ahhh...but it's best to have it there for non-techy people...

They always seem to prefer buttons to click on...
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9721658
Possibly, but I was also thinking of ease of coding for ashleycoker
0
 

Author Comment

by:ashleycoker
ID: 9721689
When I try and step through the code to see how it works, using F7 and F8 in netbeans, it crashes on the lin:

JTextField speech = new JTextField();

Netbeans hangs.  Why is this?

Ashley :-)
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9721716
> Netbeans hangs.  Why is this?

Errrr....don't know :-(

Put a breakpoint in the constuctor, and in the main method...

Don't step through the initializers?

Maybe netbeans doesn't like debugging swing stuff?

Tim.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9721719
PS:  Does it work?
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question