Solved

What code goes where?

Posted on 2003-11-11
13
326 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
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
 
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
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…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

706 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now