1

I have made a java program using sockets for a GreetingServer which waits for clients to connect. It works. The thing is I want to make a JFrame for it, having a Start Server button, for example, which starts the server. Having GreetingServer.java and GreetingServerUI.java (which is the JFrame having the button), how can I combine these 2 java files in a way that my button uses method from GreetingServer.java to start my server? This is just an example for me to start a bigger project, but I don't know this basic stuff. Thank you!

I would put my file here, but I don't know how. EDIT:

GreetingServer.java

import java.net.*;
import java.io.*;

public class GreetingServer extends Thread
{
private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException
{
   serverSocket = new ServerSocket(port);
   serverSocket.setSoTimeout(60000);
}

public void run()
{
  while(true)
  {
     try
     {
        System.out.println("Se asteapta un client pe portul " +
        serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Conectarea cu "
              + server.getRemoteSocketAddress() + " s-a facut.");
        DataInputStream in =
              new DataInputStream(server.getInputStream());
        System.out.println(in.readUTF());
        DataOutputStream out =
             new DataOutputStream(server.getOutputStream());
        out.writeUTF("Multumim ca v-ati conectat la "
          + server.getLocalSocketAddress() + "\nPa pa!");
        server.close();
     }catch(SocketTimeoutException s)
     {
        System.out.println("Timpul socketului s-a terminat!");
        break;
     }catch(IOException e)
     {
        e.printStackTrace();
        break;
     }
  }
}
public static void main(String [] args)
{
  int port = 9000;
  try
  {
     Thread t = new GreetingServer(port);
     t.start();
  }catch(IOException e)
  {
     e.printStackTrace();
  }
 }
}

And here is the GreetingServerUI.java:

import java.net.*;
import java.io.*;

public class GreetingServerUI extends javax.swing.JFrame {

/**
 * Creates new form GreetingServerUI
 */
public GreetingServerUI() {
    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() {

    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("Start Server");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(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()
            .addGap(162, 162, 162)
            .addComponent(jButton1)
            .addContainerGap(147, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(132, 132, 132)
            .addComponent(jButton1)
            .addContainerGap(145, Short.MAX_VALUE))
    );

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

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

}                                        

/**
 * @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(GreetingServerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(GreetingServerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(GreetingServerUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(GreetingServerUI.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 GreetingServerUI().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
// End of variables declaration                   

}

Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59

2 Answers2

0

Well if I'm getting you correctly you are pretty much asking this, you have to use the actionPerformed method of the JButton class. In your case you should first import the GreetingServer.java class in your GreetingServerUI.java using the import statement,

import GreetingServer.java  //if both are in same package

Then in your GreetingServerUI's jButton1ActionPerformed method

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) throws IOException{                                         
      //create a GreetingServer object and call the method you want in the
      //GreetingServer.java using dot(.) operator like for example,
      GreetingServer gServer = new GreetingServer(9000);
      gServer.run();
}
Community
  • 1
  • 1
Lucky
  • 16,787
  • 19
  • 117
  • 151
  • Thank you for your reply. I did what you said. My both java files are in the same package named greetingserver and I have the "package greetingserver;" line in both java files, but I get the error: " error: package GreetingServer does not exist import GreetingServer.java;" – Victoras Marcu Feb 18 '15 at 13:00
  • I made a class for GreetingServer.java in the same package and then I imported it import greetingserver.GreetingServer; but I receive " error: unreported exception IOException; must be caught or declared to be thrown GreetingServer gServer = new GreetingServer(9000); " – Victoras Marcu Feb 18 '15 at 13:16
  • Can you, please, help me a little more? Now I want to use instead of `System.out.println(" e.g. Connection made")` the option to write those messages in a jTextArea in the jFrame. But I don't know how to do this either, what and where to import to be able to change System.out.println() with jTextArea1.append(). – Victoras Marcu Feb 18 '15 at 14:22
  • @VictorasMarcu updated the answer..for the other thing you should probably ask a new question..if you find my solution working you can either accept the answer or upvote it.. – Lucky Feb 19 '15 at 09:06
0

I don't know if this is the right way to do it, but I think I solved it. When I press the JButton, my server starts. My JButton's actionPerformed looks like this:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    //create a GreetingServer object and call the method you want in the
  //GreetingServer.java using dot(.) operator like for example,
    int port=9000;
    try
    {
     Thread t = new GreetingServer(port);
     t.start();
    }catch(IOException e)
    { 
           e.printStackTrace();
    }
}