2012-09-29 266 views
3

我已經創建(通過從互聯網收集一些代碼片段)基於控制檯的局域網聊天應用程序。現在我想要基於控制檯的應用程序到基於Java的GUI應用程序

使用Netbeans IDE 7.1製作GUI。 它是一個多線程應用程序。 在我的基於控制檯的應用程序,每當我想顯示輸出我去做做

System.out.println(msg) . 

現在我在JFrame窗體想要做,

jTextField1.setText(msg). 

我需要創建一個新的主類並把創建一個實例的JFrameForm並使其可見通過將呼叫

new NewJFrame().setVisible(true); 

,或者我應該做的所有編碼中JFrame類本身。我出現在我的實際和工作代碼(在控制檯)下面

import java.io.DataInputStream; 
import java.io.PrintStream; 
import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.io.IOException; 
import java.net.Socket; 
import java.net.UnknownHostException; 

public class MultiThreadChatClient implements Runnable { 

    // The client socket 
    private static Socket clientSocket = null; 
    // The output stream 
    private static PrintStream os = null; 
    // The input stream 
    private static DataInputStream is = null; 

    private static BufferedReader inputLine = null; 
    private static boolean closed = false; 

    public static void main(String[] args) { 

    // The default port. 
    int portNumber = 2222; 
    // The default host. 
    String host = "127.0.0.1"; 

    if (args.length < 2) { 
     System.out 
      .println("Usage: java MultiThreadChatClient <host> <portNumber>\n" 
       + "Now using host=" + host + ", portNumber=" + portNumber); 
    } else { 
     host = args[0]; 
     portNumber = Integer.valueOf(args[1]).intValue(); 
    } 

    /* 
    * Open a socket on a given host and port. Open input and output streams. 
    */ 
    try { 
     clientSocket = new Socket(host, portNumber); 
     inputLine = new BufferedReader(new InputStreamReader(System.in)); 
     os = new PrintStream(clientSocket.getOutputStream()); 
     is = new DataInputStream(clientSocket.getInputStream()); 
    } catch (UnknownHostException e) { 
     System.err.println("Don't know about host " + host); 
    } catch (IOException e) { 
     System.err.println("Couldn't get I/O for the connection to the host " 
      + host); 
    } 

    /* 
    * If everything has been initialized then we want to write some data to the 
    * socket we have opened a connection to on the port portNumber. 
    */ 
    if (clientSocket != null && os != null && is != null) { 
     try { 

     /* Create a thread to read from the server. */ 
     new Thread(new MultiThreadChatClient()).start(); 
     while (!closed) { 
      os.println(inputLine.readLine().trim()); 
     } 
     /* 
     * Close the output stream, close the input stream, close the socket. 
     */ 
     os.close(); 
     is.close(); 
     clientSocket.close(); 
     } catch (IOException e) { 
     System.err.println("IOException: " + e); 
     } 
    } 
    } 

    /* 
    * Create a thread to read from the server. (non-Javadoc) 
    * 
    * @see java.lang.Runnable#run() 
    */ 
    public void run() { 
    /* 
    * Keep on reading from the socket till we receive "Bye" from the 
    * server. Once we received that then we want to break. 
    */ 
    String responseLine; 
    try { 
     while ((responseLine = is.readLine()) != null) { 
     System.out.println(responseLine); 
     if (responseLine.indexOf("*** Bye") != -1) 
      break; 
     } 
     closed = true; 
    } catch (IOException e) { 
     System.err.println("IOException: " + e); 
    } 
    } 
} 

//MultiThreadServer.java 


import java.io.DataInputStream; 
import java.io.PrintStream; 
import java.io.IOException; 
import java.net.Socket; 
import java.net.ServerSocket; 

/* 
* A chat server that delivers public and private messages. 
*/ 
public class MultiThreadChatServer { 

    // The server socket. 
    private static ServerSocket serverSocket = null; 
    // The client socket. 
    private static Socket clientSocket = null; 

    // This chat server can accept up to maxClientsCount clients' connections. 
    private static final int maxClientsCount = 10; 
    private static final clientThread[] threads = new clientThread[maxClientsCount]; 

    public static void main(String args[]) { 

    // The default port number. 
    int portNumber = 2222; 
    if (args.length < 1) { 
     System.out 
      .println("Usage: java MultiThreadChatServer <portNumber>\n" 
       + "Now using port number=" + portNumber); 
    } else { 
     portNumber = Integer.valueOf(args[0]).intValue(); 
    } 

    /* 
    * Open a server socket on the portNumber (default 2222). Note that we can 
    * not choose a port less than 1023 if we are not privileged users (root). 
    */ 
    try { 
     serverSocket = new ServerSocket(portNumber); 
    } catch (IOException e) { 
     System.out.println(e); 
    } 

    /* 
    * Create a client socket for each connection and pass it to a new client 
    * thread. 
    */ 
    while (true) { 
     try { 
     clientSocket = serverSocket.accept(); 
     int i = 0; 
     for (i = 0; i < maxClientsCount; i++) { 
      if (threads[i] == null) { 
      (threads[i] = new clientThread(clientSocket, threads)).start(); 
      break; 
      } 
     } 
     if (i == maxClientsCount) { 
      PrintStream os = new PrintStream(clientSocket.getOutputStream()); 
      os.println("Server too busy. Try later."); 
      os.close(); 
      clientSocket.close(); 
     } 
     } catch (IOException e) { 
     System.out.println(e); 
     } 
    } 
    } 
} 

//ChatClient.java 

/* 
* The chat client thread. This client thread opens the input and the output 
* streams for a particular client, ask the client's name, informs all the 
* clients connected to the server about the fact that a new client has joined 
* the chat room, and as long as it receive data, echos that data back to all 
* other clients. When a client leaves the chat room this thread informs also 
* all the clients about that and terminates. 
*/ 
class clientThread extends Thread { 

    private DataInputStream is = null; 
    private PrintStream os = null; 
    private Socket clientSocket = null; 
    private final clientThread[] threads; 
    private int maxClientsCount; 

    public clientThread(Socket clientSocket, clientThread[] threads) { 
    this.clientSocket = clientSocket; 
    this.threads = threads; 
    maxClientsCount = threads.length; 
    } 

    public void run() { 
    int maxClientsCount = this.maxClientsCount; 
    clientThread[] threads = this.threads; 

    try { 
     /* 
     * Create input and output streams for this client. 
     */ 
     is = new DataInputStream(clientSocket.getInputStream()); 
     os = new PrintStream(clientSocket.getOutputStream()); 
     os.println("Enter your name."); 
     String name = is.readLine().trim(); 
     os.println("Hello " + name 
      + " to our chat room.\nTo leave enter /quit in a new line"); 
     for (int i = 0; i < maxClientsCount; i++) { 
     if (threads[i] != null && threads[i] != this) { 
      threads[i].os.println("*** A new user " + name 
       + " entered the chat room !!! ***"); 
     } 
     } 
     while (true) { 
     String line = is.readLine(); 
     if (line.startsWith("/quit")) { 
      break; 
     } 
     for (int i = 0; i < maxClientsCount; i++) { 
      if (threads[i] != null) { 
      threads[i].os.println("<" + name + "&gr; " + line); 
      } 
     } 
     } 
     for (int i = 0; i < maxClientsCount; i++) { 
     if (threads[i] != null && threads[i] != this) { 
      threads[i].os.println("*** The user " + name 
       + " is leaving the chat room !!! ***"); 
     } 
     } 
     os.println("*** Bye " + name + " ***"); 

     /* 
     * Clean up. Set the current thread variable to null so that a new client 
     * could be accepted by the server. 
     */ 
     for (int i = 0; i < maxClientsCount; i++) { 
     if (threads[i] == this) { 
      threads[i] = null; 
     } 
     } 

     /* 
     * Close the output stream, close the input stream, close the socket. 
     */ 
     is.close(); 
     os.close(); 
     clientSocket.close(); 
    } catch (IOException e) { 
    } 
    } 

回答

0

我假設Netbeans IDE開發應用程序,而不是使用Netbeans平臺。有關於構建聊天客戶端的DZone博客文章。我認爲你需要根據你的問題閱讀鞦韆。這篇博客文章使用AWT,但它對你來說是一個好的開始。

http://www.javaworld.com/jw-01-1997/jw-01-chat.html

0

Java是一種面向對象的語言,所以我覺得你應該創建一個像ChatFrame一個類,這個類ChatFrame應該延長 JFrame類。 (或者可以有一個在「showChatFrame」這樣的方法中使用的JFrame的實例,thx爲這個點的Hovercraft Full Of Eels!)

所以,你可以在這個ChatFrame類中編寫每一個gui代碼並進行服務器通信代碼在另一個類中。

這是很好的編碼風格,以使用強大的模塊。你的軟件應該是幾個模塊,它們是通過接口(不是每次都是真正的Java接口)相互通信的

您的主類應該只包含主要方法,並創建一個ServerCommunication對象,該對象進行通信並使用ChatFrame類向用戶顯示消息。

+3

我同意他應該分開他的顧慮 - 有一個GUI或一系列GUI「視圖」類,並有單獨的類爲聊天機制,但一個小挑剔:我不同意有任何GUI類*擴展* JFrame,因爲通常不需要這樣做,因爲我們要通過以下方式改變JFrame的基本行爲是非常罕見的:壓倒其一種方法。 –

2

雖然嚴格來說不是原始問題的一部分,但控制檯應用程序和GUI應用程序之間存在很多非常重要的區別。

首先,線程模型是不同的,並且非常重要,您需要花時間瞭解什麼以及在哪裏以及如何使用它。首先,千萬不要在將會阻止它的Event Dispatching Thread(aka EDT)(主UI線程)中執行任何操作,例如IO操作......在可能的情況下,在後臺執行這些操作線程或worker

不要從任何線程更新任何線程的UI組件,然後是EDT。SwingWorker可以幫助在這些情況下,當它不能你需要依靠SwingUtilities.invokeLater/invokeAndWait

相關問題