Hello everyone,
I am having a problem, I want to transfer the data from a text field which is found in the class "ServerInterface" to a method in another class "Server".


I wanted to transfer data to the method "sendData()" in the class Server when the user enter data in the textfield "txtSendMessage" and click on the button "btnSend" found in ServerInterface.


I am new to Java and Socktet programming, the thing is that I have finally managed to understand socket programming after lots of hard work but my problem is that I am unable to merge my interface with the other class, could you please help me on this please.

I am send the two class as attachment.

Thanks in advance.

Attachments
package ignisv70;
import java.net.*;
import java.io.*;

public class Server extends Thread{

   private ObjectOutputStream output; // output stream to client
   private ObjectInputStream input; // input stream from client
   private ServerSocket server; // server socket
   private Socket connection; // connection to client
   private int counter = 1; // counter of number of connections

    // set up and run server
    public void run(){
        try  // set up server to receive connections; process connections
        {
            server = new ServerSocket(1234, 100); // create ServerSocket

            while(true){
                try
                {
                   waitForConnection(); // wait for a connection
                   getStreams(); // get input & output streams
                   processConnection(); // process connection
                } // end try
                catch ( EOFException eofException )
                {
                   displayMessage( "\nServer terminated connection" );
                } // end catch
                finally
                {
                   closeConnection(); //  close connection
                   counter++;
                } // end finally
            }

        }//end try
        catch ( IOException ioException )
        {
             ioException.printStackTrace();
        } // end catch
    } // end method runServer






    // wait for connection to arrive, then display connection info
   private void waitForConnection() throws IOException
   {
       displayMessage( "Waiting for connection\n" );
       connection = server.accept(); // allow server to accept connection
       displayMessage( "Connection " + counter + " received from: " +  connection.getInetAddress().getHostName() );
   }//end method waitForConnection





   // get streams to send and receive data
   private void getStreams() throws IOException
   {

      // set up output stream for objects
      output = new ObjectOutputStream( connection.getOutputStream() );
      output.flush(); // flush output buffer to send header information

      // set up input stream for objects
      input = new ObjectInputStream( connection.getInputStream() );

      displayMessage( "\nGot I/O streams\n" );
   } // end method getStreams





   // process connection with client
   private void processConnection() throws IOException
   {
      String message = "Connection successful";
      sendData( message ); // send connection successful message

      // enable enterField so server user can send messages
      //setTextFieldEditable( true ); +++++++++++++++++++++

      do // process messages sent from client
      {
         try // read message and display it
         {
            message = ( String ) input.readObject(); // read new message
            displayMessage( "\n" + message ); // display message
         } // end try
         catch ( ClassNotFoundException classNotFoundException )
         {
            displayMessage( "\nUnknown object type received" );
         } // end catch

      } while ( !message.equals( "CLIENT>>> TERMINATE" ) );
   } // end method processConnection





   // close streams and socket
   private void closeConnection()
   {
      displayMessage( "\nTerminating connection\n" );
      //setTextFieldEditable( false ); // disable enterField +++++++++++++

      try
      {
         output.close(); // close output stream
         input.close(); // close input stream
         connection.close(); // close socket
      } // end try
      catch ( IOException ioException )
      {
         ioException.printStackTrace();
      } // end catch
   } // end method closeConnection






   // send message to client
   public void sendData( String message )
   {
      try // send object to client
      {
         output.writeObject( "SERVER>>> " + message );
         output.flush(); // flush output to client
         displayMessage( "\nSERVER>>> " + message );
      } // end try
      catch ( IOException ioException )
      {
         //displayArea.append( "\nError writing object" );+++++++++++++++
      } // end catch
   } // end method sendData





   private void displayMessage( final String messageToDisplay )
   {


   }




   /*
   // manipulates displayArea in the event-dispatch thread
   private void displayMessage( final String messageToDisplay )
   {
      SwingUtilities.invokeLater(
         new Runnable()
         {
            public void run() // updates displayArea
            {
               displayArea.append( messageToDisplay ); // append message
            } // end method run
         } // end anonymous inner class
      ); // end call to SwingUtilities.invokeLater
   } // end method displayMessage

    */










}// end the class
package ignisv70;
import java.net.*;
import java.io.*;
import javax.swing.JFrame;


public class ServerInterface extends JFrame {

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

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtChatBox = new javax.swing.JTextArea();
        txtSendMessage = new javax.swing.JTextField();
        btnSend = new javax.swing.JButton();
        btnActivateServer = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("iGnis Server");

        txtChatBox.setColumns(20);
        txtChatBox.setRows(5);
        jScrollPane1.setViewportView(txtChatBox);

        btnSend.setText("Send");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        btnActivateServer.setText("Activate Server");
        btnActivateServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActivateServerActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtSendMessage, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnSend, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnActivateServer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(53, 53, 53)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnActivateServer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtSendMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(30, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-417)/2, (screenSize.height-327)/2, 417, 327);
    }// </editor-fold>//GEN-END:initComponents

    private void btnActivateServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActivateServerActionPerformed

        try
        {
                //  this.start();

        } // end try
        catch(Exception e){e.printStackTrace();}

    }//GEN-LAST:event_btnActivateServerActionPerformed

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed
         // Server.sendData("hello");
    }//GEN-LAST:event_btnSendActionPerformed


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ServerInterface().setVisible(true);
                Server cs1 = new Server();
                cs1.start();
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnActivateServer;
    private javax.swing.JButton btnSend;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtChatBox;
    private javax.swing.JTextField txtSendMessage;
    // End of variables declaration//GEN-END:variables


}// end of class

Good morning neutralfox. Wow, that server code really has been cleaned up!
All you need to do in response to the button being clicked is to get the text from the input field and pass it as the parameter to the server's send method. The only problem I see in your code is that the send method is an instance method, and you were trying to invoke it as a class method. ie instead of Server.sendData it should be cs1.sendData.
ps. Maybe a good time to mark the previous thread as "solved"?

Hello, Good Morning to you too. Already marked as solved.

Concerning my new problem, I am unable to send the message to the method sendData() . I have tried your solution i.e cs1.sendData, still not working.

I think the problem is because I have instantiated the cs1 in the main and the button event is not detecting that instance.

public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ServerInterface().setVisible(true);
                Server cs1 = new Server();
                cs1.start();
               
               
            }
        });
    }

Please give me the solution to pass the data to the sendData() method when the button is clicked.

If I used cs1.sendData as you mentioned. Netbeans does not detect the cs1._________ because the instance cs1 have been instantiated in the main. This is what I have understand, maybe I am wrong !!

Its the first time I am using NetBeans GUI Builder, I don't know how to merge these 2 classes together. That is, how to call a method from an other class on an action event in the GUI(another class). Note: The program in working well without the GUI.


Thanks in advance.

When you create the GUI, pass the server instance (cs1) as a parameter to the GUI's constructor. (You need to write a very short constructor that just saves the server reference then calls the default constructor) That way the GUI will have a reference to the server instance and will be able to call its methods.

Server cs1 = new Server();
 new ServerInterface(cs1).setVisible(true);

Thanks a lot for the answer but its too complicated for me. I have not been able to implement what you just said. Could you please give me an example.

You need to write a very short constructor that just saves the server reference then calls the default constructor

Its this part that I have not understood.

Thanks in advance James.

The new constructor for ServerInterface needs to look like this:

Server theServer; // Add a variable to the GUI class to hold a reference to the server
public ServerInterface(Server s) { // add a new constructor that takes a server reference as parameter
theServer = s; // save a ref to the server
this(); // call the original (default) constructor
}

I have tried it but still not working, I am getting some errors. I am sending the ServerInterface() with the modification, check it out please.

Attachments
package ignisv70;
import java.net.*;
import java.io.*;
import javax.swing.JFrame;


public class ServerInterface extends JFrame {

    /** Creates new form ServerInterface */

    Server theServer; // Add a variable to the GUI class to hold a reference to the server

   public ServerInterface(Server s) { // add a new constructor that takes a server reference as parameter
        theServer = s; // save a ref to the server
         initComponents();
//        this(); // call the original (default) constructor
    }

//
//    public ServerInterface() {
//        initComponents();
//    }






    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtChatBox = new javax.swing.JTextArea();
        txtSendMessage = new javax.swing.JTextField();
        btnSend = new javax.swing.JButton();
        btnActivateServer = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("iGnis Server");

        txtChatBox.setColumns(20);
        txtChatBox.setRows(5);
        jScrollPane1.setViewportView(txtChatBox);

        btnSend.setText("Send");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        btnActivateServer.setText("Activate Server");
        btnActivateServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActivateServerActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtSendMessage, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnSend, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnActivateServer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(53, 53, 53)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnActivateServer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtSendMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSend, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(30, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-417)/2, (screenSize.height-327)/2, 417, 327);
    }// </editor-fold>                        

    private void btnActivateServerActionPerformed(java.awt.event.ActionEvent evt) {                                                  

        try
        {
                //  this.start();

        } // end try
        catch(Exception e){e.printStackTrace();}

    }                                                 

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {                                        
        cs1.sendData("hello"); // I am getting an error over here
     
    }                                       





    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Server cs1 = new Server();
                new ServerInterface(cs1).setVisible(true); // according to James
                cs1.start();
               
               
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnActivateServer;
    private javax.swing.JButton btnSend;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtChatBox;
    private javax.swing.JTextField txtSendMessage;
    // End of variables declaration                   


}// end of class

I the new variable is called theServer, but your call refers to cs1 (which is the variable in the main class, not the one in the GUI). so it would be
theServer.sendData
You original version of the constructors was right, so is the commented latest version, but you may find a problem when netbeans regenerates its code unless you stick to the first version.

Wooowww Wowwww .... You are a genius, its working. If ever you came to Mauritius, I will buy you a beer. Really you rocks. :D.

This question has already been answered. Start a new discussion instead.