• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 353
  • Last Modified:

What code goes where?

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
ashleycoker
Asked:
ashleycoker
1 Solution
 
CEHJCommented:
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
 
CEHJCommented:
Or that could be

public void sendMessage(BufferedWriter out) {

}

public void receiveMessage(BufferedReader in) {

}


0
 
jimmackCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
TimYatesCommented:
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
 
CEHJCommented:
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
 
TimYatesCommented:
Dang...too slow :-(
0
 
TimYatesCommented:
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
 
CEHJCommented:
>>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
 
TimYatesCommented:
ahhh...but it's best to have it there for non-techy people...

They always seem to prefer buttons to click on...
0
 
CEHJCommented:
Possibly, but I was also thinking of ease of coding for ashleycoker
0
 
ashleycokerAuthor Commented:
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
 
TimYatesCommented:
> 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
 
TimYatesCommented:
PS:  Does it work?
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now