10 Replies - 4495 Views - Last Post: 21 March 2013 - 03:12 AM Rate Topic: -----

#1 Blah4569  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 09-March 13

Adding Swing GUI to a UDP Chat Program

Posted 09 March 2013 - 10:32 PM

I created this UDP Chat program recently and these past few days I have been trying to add a Swing GUI on it to make it nicer and much better to use than the normal netbeans debug. This is the first time I have ever tried to use Swing and I am lost and need help with this topic. I have tried to do simple things like to have the class add text to a label or a textbox but it always comes up as "Error1java.lang.NullPointerException". Here is are my classes I am using.

Main Class


public class Main
{

    public static void main(String[] args) throws Exception
    {
        new ChatGUI().setVisible(true);
        UDPServer myServer = new UDPServer();
        UDPClient myClient = new UDPClient();
        myServer.start();
        myClient.start();
        
    }

}



Client Class

import java.net.*;
import java.io.*;
import java.util.Random;

public class UDPClient extends Thread
{
    ChatGUI gui;

       // The key for 'encrypting' and 'decrypting'.
       static final String key = "Encrypt"; 
       //Simulate packet loss rate
       private static final double LOSS_RATE = 0.3;
       
       public static String encryptString(String str)
   {
      StringBuffer sb = new StringBuffer (str);
      int lenStr = str.length();
      int lenKey = key.length();	
      // For each character in our string, encrypt it...
      for ( int i = 0, j = 0; i < lenStr; i++, j++ ) 
      {
         if ( j >= lenKey ) j = 0;  // Wrap 'round to beginning of key string.
          // XOR the chars together. Must cast back to char to avoid compile error. 
         sb.setCharAt(i, (char)(str.charAt(i) ^ key.charAt(j))); 
      }
      return sb.toString();
   }
   
       
  public void run()
  {
      //create random number generator for use in simulated packet loss.
       Random random = new Random();
    try
    {
      // Specify size of UDP chunk to send
      byte[] send_data = new byte[1024];
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));//Create input stream
      DatagramSocket client_socket = new DatagramSocket(); //Create a client socket 
      InetAddress IPAddress =  InetAddress.getByName("localhost"); //Translate hostname to IP address using dns

      while (true)
      {

      	System.out.println("Type Something (q or Q to quit): ");
        String data = inFromUser.readLine();
        //String s1 = data;
        data = encryptString(data);
        
      	if (data.equals("q") || data.equals("Q"))
      	break;

      	else
      	{         
      	send_data = data.getBytes();
        
        //Create datagram packet with data-to-send, length, IP address, port
        DatagramPacket send_packet = new DatagramPacket(send_data,
                                                        send_data.length,
                                                        IPAddress, 5002);
         // Decide whether to reply, or simulate packet loss.
         if (random.nextDouble() < LOSS_RATE) {
            System.out.println("Message not sent."); 
            System.out.println("Attempting to resend.");
            System.out.println("Successfully resent," + "You wrote:     " + data);
            client_socket.send(send_packet);
        
         }
         else
        //Send datagram to server
        client_socket.send(send_packet);        
        System.out.println("You wrote:     " + data);   
        gui.setTexter("Hello");
        gui.setLabel("Hello");
        }
      }
      client_socket.close();
      System.exit(0);
   }
   catch (Exception e)
   {
      System.out.println("Error1" + e);
   }
 }
}



Server Class

import java.net.*;
import java.util.Random;
//import java.io.*;

public class UDPServer extends Thread
{
   public void run()
   {
      int measure;   
     // Specify size of UDP chunk to receive
      byte[] receive_data = new byte[1024];
       try
       {           
        //Create a datagram socket at port
         DatagramSocket server_socket = new DatagramSocket(5001);
         System.out.println ("UDPServer Waiting for client");
         while(true)
         {
        //Create the space for received datagram 
          DatagramPacket receive_packet = new DatagramPacket(receive_data,
                                              receive_data.length);
                  //Receive the datagram
                  server_socket.receive(receive_packet);

                  String data = new String(receive_packet.getData(),0
                                           ,receive_packet.getLength());
                  String s1 = data;
                  data = UDPClient.encryptString(s1);
                 
                 measure = receive_packet.getLength();
                   //Get the IP address from the sender
                  InetAddress IPAddress = receive_packet.getAddress();                  

                  if (data.equals("q") || data.equals("Q"))
                  break;
                  else

                  System.out.println("( " + IPAddress + " , " +
                    measure +  " ) They said :" + data );
         }
      }
       catch(Exception e)
       {
           System.out.println("Error2" + e);
       }
   }
}



ChatGUI

public class ChatGUI extends javax.swing.JFrame {

    /**
     * Creates new form ChatGUI
     */
    public ChatGUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextField1.setText("jTextField1");

        jLabel1.setText("jLabel1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(160, 160, 160)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(78, 78, 78)
                        .addComponent(jLabel1)))
                .addContainerGap(181, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(87, 87, 87)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 124, Short.MAX_VALUE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(55, 55, 55))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ChatGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ChatGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration

    public void setTexter(String s ) { // the setter method to set text of "jTextField1"
        jTextField1.setText(s);
    }
    public void setLabel(String s ) { // the setter method to set text of "jTextField1"
        jLabel1.setText(s);
    }

}



Is This A Good Question/Topic? 0
  • +

Replies To: Adding Swing GUI to a UDP Chat Program

#2 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • View blog
  • Posts: 2,533
  • Joined: 29-July 11

Re: Adding Swing GUI to a UDP Chat Program

Posted 10 March 2013 - 05:01 AM

You need to be more specific. Post the exact error message you get, please. Most of us won't comb through your code line by line.
Was This Post Helpful? 0
  • +
  • -

#3 Blah4569  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 09-March 13

Re: Adding Swing GUI to a UDP Chat Program

Posted 10 March 2013 - 08:43 PM

This is the error I get Error1java.lang.NullPointerException
It happens when the program reaches this part of the Client Class

gui.setTexter("Hello");
gui.setLabel("Hello");


Was This Post Helpful? 0
  • +
  • -

#4 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 823
  • View blog
  • Posts: 2,533
  • Joined: 29-July 11

Re: Adding Swing GUI to a UDP Chat Program

Posted 11 March 2013 - 01:01 PM

You need to post a stack trace, the bunch of red text that pops up in your ide. Something has not been initialized.
Was This Post Helpful? 0
  • +
  • -

#5 Takk  Icon User is offline

  • D.I.C Head

Reputation: 40
  • View blog
  • Posts: 111
  • Joined: 08-March 13

Re: Adding Swing GUI to a UDP Chat Program

Posted 11 March 2013 - 01:17 PM

Looks like instead of using gui.method, you should be using ChatGUI.method, although I don't actually see where these lines are at in your original code.
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8327
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Adding Swing GUI to a UDP Chat Program

Posted 11 March 2013 - 05:03 PM

Avoid GUI generators. Write your own GUI you won't end up with code you won't understand
Was This Post Helpful? 0
  • +
  • -

#7 Blah4569  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 09-March 13

Re: Adding Swing GUI to a UDP Chat Program

Posted 12 March 2013 - 06:13 PM

The main reason i was using a GUI generator was because i have not worked with swing(but have with VB and ASP.net) before and my next part of the project will be to create a networked Tic-Tac-Toe application using TCP that will work under the same GUI next to the chat. I dont believe making the Tic-Tac-Toe will give me problems but making it connect to same GUI as the chat and work together will because of never working with swing in the past. any recommendations? Im just really confused at the moment.
Was This Post Helpful? 0
  • +
  • -

#8 Takk  Icon User is offline

  • D.I.C Head

Reputation: 40
  • View blog
  • Posts: 111
  • Joined: 08-March 13

Re: Adding Swing GUI to a UDP Chat Program

Posted 20 March 2013 - 03:45 AM

Just start working through Swing tutorials, the more basic the better. Start with adding the frame and a button and get your event responders registered and working for that button and go from there, it's a pretty basic concept as far as that goes, then go from there.
Was This Post Helpful? 0
  • +
  • -

#9 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2675
  • View blog
  • Posts: 11,305
  • Joined: 20-September 08

Re: Adding Swing GUI to a UDP Chat Program

Posted 20 March 2013 - 03:55 AM

Quote

        new ChatGUI().setVisible(true);
        UDPServer myServer = new UDPServer();
        UDPClient myClient = new UDPClient();
        myServer.start();
        myClient.start();

You have three independent class initializations there with seemingly no interconnection whatever. How can you expect not to get NPEs?
Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8327
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Adding Swing GUI to a UDP Chat Program

Posted 20 March 2013 - 07:24 PM

View PostBlah4569, on 12 March 2013 - 09:13 PM, said:

The main reason i was using a GUI generator was because i have not worked with swing(but have with VB and ASP.net) before and my next part of the project will be to create a networked Tic-Tac-Toe application using TCP that will work under the same GUI next to the chat. I dont believe making the Tic-Tac-Toe will give me problems but making it connect to same GUI as the chat and work together will because of never working with swing in the past. any recommendations? Im just really confused at the moment.

That is the big problem with VB people using it usually start by making the GUI and then try to implement the code in the generated method stub.

The user interface (GUI, console)
the business rules (the same 3 in row/column/diagonal win)
the data (let say you save the score results in a file, database, in memory)

should be completly independant
If you replace the console by a GUI the business rules part shouldn';t requie modificationj and the data part neither.

If you swith fromflat file to SQL database, the GUI part and the business rules part shouldn't change.

If you use a GUI generator you won't be able not to make a spagetti out of all that.

A TicTacToe and the control buttons shouldn't be complicated
Was This Post Helpful? 0
  • +
  • -

#11 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2675
  • View blog
  • Posts: 11,305
  • Joined: 20-September 08

Re: Adding Swing GUI to a UDP Chat Program

Posted 21 March 2013 - 03:12 AM

Quote

should be completly independant
... and it should be no different, whatever language you're working in (including VB ;))
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1