2014-04-06 40 views
0

我正在創建一個客戶端 - 服務器聊天程序。我已經爲服務器和客戶端編寫了代碼。我現在想要做的就是讓連接用戶的列表到文本區域。我有一個按鈕「獲取用戶」。但這個按鈕沒有做任何事情。但是當我從文本字段中輸入「!getusers」時,它可以檢索連接的用戶列表。我之前沒有和swing一起工作過。發現很難發現錯誤。這裏是我的代碼有關擺動程序的困惑

對於客戶端:=

public class ChatClient extends JFrame implements ActionListener { 
String uname; 
PrintWriter pw; 
BufferedReader br; 
JTextArea taMessages, taUserList; 
JTextField tfInput; 
JButton btnSend, btnExit,btnGetUsers; 
Socket client; 

public ChatClient(String uname, String servername) throws Exception { 
    super("Connected as: " + uname); // set title for frame 
    this.uname = uname; 
    client = new Socket(servername, 9999); 
    br = new BufferedReader(new InputStreamReader(client.getInputStream())); 
    pw = new PrintWriter(client.getOutputStream(), true); 
    pw.println(uname); // send name to server 
    //bring up the chat interface 
    buildInterface(); 
    new MessagesThread().start(); // create thread that listens for messages 
} 

public void buildInterface() { 
    btnSend = new JButton("Send"); 
    btnExit = new JButton("Exit"); 
    btnGetUsers=new JButton("Get Users"); 
    //chat area 
    taMessages = new JTextArea(); 
    taMessages.setRows(10); 
    taMessages.setColumns(50); 
    taMessages.setEditable(false); 
    //online users list 
    taUserList = new JTextArea(); 
    taUserList.setRows(10); 
    taUserList.setColumns(10); 
    taUserList.setEditable(false); 
    //top panel (chat area and online users list 
    JScrollPane chatPanel = new JScrollPane(taMessages, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 
    JScrollPane onlineUsersPanel = new JScrollPane(taUserList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); 
    JPanel tp = new JPanel(new FlowLayout()); 
    tp.add(chatPanel); 
    tp.add(onlineUsersPanel); 
    add(tp, "Center"); 
    //user input field 
    tfInput = new JTextField(50); 
    //buttom panel (input field, send and exit) 
    JPanel bp = new JPanel(new FlowLayout()); 
    bp.add(tfInput); 
    bp.add(btnSend); 
    bp.add(btnExit); 
    bp.add(btnGetUsers); 
    add(bp, "South"); 
    btnSend.addActionListener(this); 
    tfInput.addActionListener(this);//allow user to press Enter key in order to send message 
    btnExit.addActionListener(this); 
    setSize(500, 300); 
    setVisible(true); 
    pack(); 
} 

@Override 
public void actionPerformed(ActionEvent evt) { 
    if (evt.getSource() == btnExit) { 
     pw.println("!end"); // send end to server so that server know about the termination 
     System.exit(0); 
    }else if(tfInput.getText().contains("!getusers")){ 
      pw.println("!getusers"); 
    }else if(evt.getSource()== btnGetUsers){ 
     pw.println("!getusers");// send get users to the server (NOT WORKING) 
    } 
    else{ 
     // send message to server 
     pw.println(tfInput.getText()); 
    } 
} 

public static void main(String args[]) { 

    // take username from user 
    String name = JOptionPane.showInputDialog(null, "Enter your name: ", "Username", 
      JOptionPane.PLAIN_MESSAGE); 
    String servername = "localhost"; 
    try { 
     new ChatClient(name, servername); 
    } catch (Exception ex) { 
     out.println("Unable to connect to server.\nError: " + ex.getMessage()); 
    } 

} // end of main 

// inner class for Messages Thread 
class MessagesThread extends Thread { 

    @Override 
    public void run() { 
     String line; 
     try { 
      while (true) { 
       line = br.readLine(); 
       taMessages.append(line + "\n"); 
       taMessages.setCaretPosition(taMessages.getDocument().getLength());//auto scroll to last message 
      } // end of while 
     } catch (Exception ex) { 
     } 
    } 
    } 
} // end of client 

對於服務器:=

public class ChatServer { 

    List<String> users = new ArrayList<String>(); 
    List<HandleClient> clients = new ArrayList<HandleClient>(); 

    public void process() throws Exception { 
     ServerSocket server = new ServerSocket(9999); 
     out.println("Server Started..."); 
     while (true) { 
      Socket client = server.accept(); 
      //add incoming client to connected clients vector. 
      HandleClient c = new HandleClient(client); 
      clients.add(c); 
     } // end of while 
    } 

    public static void main(String... args) throws Exception { 
     new ChatServer().process(); 
    } // end of main 

    public void broadcast(String user, String message) { 
     // send message to all connected users 
     for (HandleClient c : clients) { 
      c.sendMessage(user, message); 
     } 
    } 

    /* 
    * Inner class, responsible of handling incoming clients. 
    * Each connected client will set as it's own thread. 
    */ 
    class HandleClient extends Thread { 

     String name = "";//client name/username 
     BufferedReader input;//get input from client 
     PrintWriter output;//send output to client 

     public HandleClient(Socket client) throws Exception { 
      // get input and output streams 
      input = new BufferedReader(new InputStreamReader(client.getInputStream())); 
      output = new PrintWriter(client.getOutputStream(), true); 
      // read name 
      name = input.readLine(); 
      users.add(name); // add to users vector 
      broadcast(name, " Has connected!"); 
      start(); 
     } 

     public void sendMessage(String uname, String msg) { 
      output.println(uname + ": " + msg); 
     } 

     public void getOnlineUsers() { 

      for (HandleClient hc:clients) { 
       broadcast("", hc.name); 

      } 
     } 

     public String getUserName() { 
      return name; 
     } 

     public void run() { 
      String line; 
      try { 
       while (true) { 
        line = input.readLine(); 
        if (line.equals("!end")) { 
         //notify all for user disconnection 
         broadcast(name, " Has disconnected!"); 
         clients.remove(this); 
         users.remove(name); 
         break; 
        } else if (line.equals("!getusers")) { 
         getOnlineUsers(); 

        } 
        broadcast(name, line); // method of outer class - send messages to all 
       } // end of while 
      } // try 
      catch (Exception ex) { 
       System.out.println(ex.getMessage()); 
      } 
     } // end of run() 
    } // end of inner class 
} // end of Server 

另外,我想重定向連接到服務器上的文本區域的客戶端列表「taUserList 「(當我點擊」獲取用戶「按鈕時)。有人可以幫助我嗎?

+0

爲什麼沒有人回答我的問題? :O – arindrajit

+1

因爲本網站上的人員更願意回答問題,所以不要調試其他人的代碼。 – arcy

+0

在這裏閱讀有關如何發佈代碼示例:http://stackoverflow.com/help/mcve –

回答

2

你永遠不會添加任何動作偵聽器到按鈕。所以當它被點擊時,沒有任何反應。

+0

非常感謝.. – arindrajit