我有一个 GreetingServer.java (使用套接字)。想为它制作一个 JFrame

I have a GreetingServer.java (using sockets). Want to make a JFrame for it

我制作了一个 java 程序,它使用 GreetingServer 的套接字等待客户端连接。有用。问题是我想为它制作一个 JFrame,例如,有一个启动服务器按钮,它可以启动服务器。有 GreetingServer.javaGreetingServerUI.java(这是有按钮的 JFrame),我如何以我的按钮使用 [=15 中的方法的方式组合这 2 个 java 文件=] 启动我的服务器? 这只是我开始一个更大项目的一个例子,但我不知道这些基本的东西。谢谢!

我会把我的文件放在这里,但我不知道怎么放。 编辑:

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();
  }
 }
}

这里是 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                   

}

好吧,如果我没听错的话,您几乎是在询问 JButton class 的 this, you have to use the actionPerformed 方法。在您的情况下,您应该首先使用 import 语句

GreetingServerUI.java 中导入 GreetingServer.java class
import GreetingServer.java  //if both are in same package

然后在你的GreetingServerUIjButton1ActionPerformed方法中

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();
}

我不知道这样做是否正确,但我想我已经解决了。当我按下 JButton 时,我的服务器启动。 我的 JButton 的 actionPerformed 看起来像这样:

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();
    }
}