2011-08-25 73 views
0

我很抱歉,我在這裏遇到問題,請相信我儘可能地嘗試了。但不幸的是,在想要尋求幫助之前無法得到它的後面。並且預先感謝您的時間和精力。如何在java聊天中更新JList

我正在嘗試更新我的客戶端JList(userList),以便在新客戶端進來時,初始客戶端將被更新。但是目前,當有一個客戶端時,它可以看到自己,但是當另一個客戶端進入聊天時,只有該客戶端看到兩個連接的客戶端,初始客戶端不會更新JList上的名稱。 請幫助簡化任何答案,因爲我不擅長於Java。謝謝!

的ClientChat代碼:

import java.io.*; 
import java.net.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

    public class ClientChat extends JFrame { 
private Toolkit toolkit; 
private JLabel msgLabel; 
private JButton sendBtn; 
private JTextArea genMsg; 
public static JList userList; 
private JTextField msgF; 
private ObjectOutputStream output; 
private ObjectInputStream input; 
private Socket client; 
private String chatServer; 
private int serverport; 
private String Client_name; 

public ClientChat(String host, int port,String C_Name){ 

    // set server to which this client connects 
    chatServer = host; 
    serverport = port; 
    Client_name = C_Name; 


    toolkit = Toolkit.getDefaultToolkit();  
    if(toolkit.getScreenSize().getWidth() > 600) 
     setSize(600, 605); 
    else 
     setSize((int)toolkit.getScreenSize().getWidth(),(int)toolkit.getScreenSize().getHeight() - 20);   
     setResizable(false); 
     Dimension dimension = getSize();  
     setLayout(new FlowLayout()); 

     setTitle("FRESHER MARKETING COMPANY");  
     addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0);}}); 

     Container container = getContentPane(); 
     container.setLayout(new FlowLayout()); 

     // create General Message Screen 
     genMsg = new JTextArea(30,43); 
     genMsg.setEditable(false); 
     genMsg.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N 
     container.add(new JScrollPane(genMsg)); 
     JPanel genMsgPanel = new JPanel(); 
     genMsgPanel.setLayout(new BorderLayout()); 
     genMsgPanel.add(new JScrollPane(genMsg), BorderLayout.EAST); 
     genMsgPanel.setBorder(BorderFactory.createLineBorder(Color.black)); 
     container.add(genMsgPanel); 

     // create Friend List View 
     userList = new JList(); 
     userList.setPreferredSize(new Dimension(150,423)); 
     userList.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N 
     container.add(userList); 
     JPanel userListPanel = new JPanel(); 
     userListPanel.setLayout(new BorderLayout()); 
     userListPanel.add(userList, BorderLayout.CENTER); 
     userListPanel.setBorder(BorderFactory.createLineBorder(Color.black)); 
     container.add(userListPanel); 

     msgLabel = new JLabel ("Message:"); 
     container.add(msgLabel); 
     JPanel msgFPanel = new JPanel(); 
     msgFPanel.setLayout(new BorderLayout()); 
     msgFPanel.add(new JScrollPane(msgLabel), BorderLayout.WEST); 
     container.add(msgFPanel); 

     // create Message Field 
     msgF = new JTextField(37); 
     msgF.setEnabled(true); 
     msgF.setText(""); 
     msgF.requestFocus(); 
     msgF.addActionListener(
      new ActionListener() { 

      // send message to server 
       public void actionPerformed(ActionEvent event) 
       { 
        //sendData(event.getActionCommand()); 
       } 
      } // end anonymous inner class 
      ); // end call to addActionListener 
     msgFPanel.add(new JScrollPane(msgF), BorderLayout.CENTER); 
      } 
public void runClient() 
{ 
    // connect to server, get streams, process connection 
    try { 
     // Step 1: Create a Socket to make connection 
     connectToServer(); 
     // Step 2: Get the input and output streams 
     getStreams(); 
     handShake(); 
    }// server closed connection 
    catch (EOFException eofException) { 
     System.out.println("Server terminated connection"); 
    } 

    // process problems communicating with server 
    catch (IOException ioException) { 
     ioException.printStackTrace(); 
    } 
} 
private void connectToServer() throws IOException 
{ 
    genMsg.setText("Attempting connection\n"); 
    // create Socket to make connection to server 
    client = new Socket(InetAddress.getByName(chatServer), serverport); 
    // display connection information 
    genMsg.append("Connected to: " +client.getInetAddress().getHostName()); 
} 

private void getStreams() throws IOException 
{ 
    // set up output stream for objects 
    output = new ObjectOutputStream(client.getOutputStream()); 
    // flush output buffer to send header information 
    output.flush(); 
} 
private void handShake() throws IOException 
{ 
    String message; 
    String value[]; 
    value = new String [100]; 
    try { 
    output.writeObject(Client_name); 
    output.flush(); 
    input = new ObjectInputStream(client.getInputStream()); 
    genMsg.append("\n Client Name Send" ); 
    message = (String) input.readObject(); 
    int i=0; 
    while (!message.equals(".")){ 

     //genMsg.append("\n"+message); 
     value[i++] =message; 
     message = (String) input.readObject(); 
    } 
    userList.setListData(value); 
    message = (String) input.readObject(); 
    genMsg.append("\n"+message); 
    } 
    // process problems sending object 
    catch (IOException ioException) { 
     genMsg.append("\nError writing object"); 
    } 
    catch (ClassNotFoundException classNotFoundException) { 
     System.out.println("\nUnknown object type received"); 
     } 

} 
public static void main(String args[]) { 

    ClientChat application; 
    application = new ClientChat("127.0.0.1",5130,args[0]); 
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    application.runClient(); 
    } 
} 

的ServerChat代碼:

import java.io.*; 
import java.net.*; 
import java.util.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class ServerChat extends JFrame 
{ 
private ObjectInputStream input; 
private ObjectOutputStream output; 
private JTextField enterField; 
public static JTextArea displayArea; 
private ServerSocket server; 
private Socket connection; 
private ServerThread c1[]; 
//private Client Cname; 
private static String clientList[]; 
private int counter = 0; 

public ServerChat() 
{ 
    super("Server"); 
    Container container = getContentPane(); 
    clientList = new String[100]; 
    // create enterField and register listener 
    enterField = new JTextField(); 
    enterField.setEnabled(false); 
    enterField.addActionListener(

    new ActionListener() { 
     // send message to client 
     public void actionPerformed(ActionEvent event) 
     { 
      //sendData(event.getActionCommand()); 
     } 
    } // end anonymous inner class 
    ); // end call to addActionListener 

    container.add(enterField, BorderLayout.NORTH); 
    // create displayArea 
    displayArea = new JTextArea(); 
    container.add(new JScrollPane(displayArea), BorderLayout.CENTER); 
    setSize(300, 150); 
    setVisible(true); 
} 
public void runServer() 
{ 
    // set up server to receive connections; 
    // process connections 
    try { 
    // Step 1: Create a ServerSocket. 
    server = new ServerSocket(5130, 100); 
    c1 = new ServerThread[100]; 
    while (true) { 
     // Step 2: Wait for a connection. 
     waitForConnection(); 
     handShake(); 
     displayArea.append("\nHanshake Complete"); 
     //c1[counter] = new ServerThread(connection,counter); 
     //c1[counter].start(); 
     ++counter; 
     } 
    } 
    // process EOFException when client closes connection 
    catch (EOFException eofException) { 
    System.out.println("Client terminated connection"); 
    } 
    // process problems with I/O 
    catch (IOException ioException) { 
    ioException.printStackTrace(); 
    } 
} 
private void waitForConnection() throws IOException 
{ 
    displayArea.append("\nWaiting for connection "); 
    // allow server to accept a connection 
    connection = server.accept(); 
    displayArea.append("\nClient connected : Client"); 
} 
private void handShake() throws IOException 
{ 
    output = new ObjectOutputStream(connection.getOutputStream()); 
    output.flush(); 
    String message; 
    input = new ObjectInputStream(connection.getInputStream()); 
    try { 
     message = (String) input.readObject(); 
     clientList[counter]= message; 
     displayArea.append("\nClient connected : "+message); 
     for (int i=0; i<=counter;i++) 
     { 
      output.writeObject(clientList[i]); 
      output.flush(); 
     } 
     output.writeObject("."); 
     output.flush(); 
     } 
    // catch problems reading from client 
    catch (ClassNotFoundException classNotFoundException) { 
     System.out.println("\nUnknown object type received"); 
     } 
     catch (IOException ioException) { 
    ioException.printStackTrace(); 
    } 
} 
public static void main(String args[]) 
{ 
    ServerChat application = new ServerChat(); 
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    application.runServer(); 
} 
} 

的ServerThread代碼:

import java.io.*; 
import java.net.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
public class ServerThread extends Thread 
{ 
private Socket connection; 
private ObjectOutputStream output; 
private ObjectInputStream input; 
private int counter; 
public ServerThread(Socket con,int count) 
{ 
    connection = con; 
    counter = count; 

} 
public void run() 
{ 
     try 
     { 
      getStreams(); 
      processConnection(); 
     } 
     // process EOFException when client closes connection 
    catch (EOFException eofException) { 
    System.out.println("Client terminated connection"); 
    } 

    // process problems with I/O 
    catch (IOException ioException) { 
    ioException.printStackTrace(); 
    } 
} 
    private void getStreams() throws IOException 
    { 
    // set up output stream for objects 
    output = new ObjectOutputStream(connection.getOutputStream()); 
    // flush output buffer to send header information 
    output.flush(); 
    output.writeObject("SERVER>>> Connection successful"); 
    output.flush(); 
    } 
private void processConnection() throws IOException 
{ 
    // send connection successful message to client 
    String message = "SERVER>>> Connection successful"; 

    output.writeObject(message); 
    output.flush(); 
} 
private void closeConnection() throws IOException 
{ 
    ServerChat.displayArea.append("\nUser terminated connection"); 

    output.close(); 
    input.close(); 
    connection.close(); 
    } 
} 
+0

確定變更的所有方法,讓你的服務器端代碼只向用戶發送更新到新連接的客戶端,但不exsiting用戶。此外,我沒有看到通知其模型更改列表的代碼。 – Saint

回答

2

你有真正的問題Concurency in Swing,從BackGround Tasks所有輸出必須是包裝成invokeLater(),如果你在這裏iting可能的,並且重複網絡故障(或多個)則更好。將進入invokeAndWait()

1)只創建一個方法,用於加/追加字符串到JTextArea

2)方法中添加/追加字符串到JTextArea渦捲到了invokeLater()

3)檢查這個thread和修改/給出例子

+0

感謝您的回覆。 但我不明白 – user863550

+0

@ user863550,你不能直接調用JList方法。您必須調用SwingUtilities.invokeLater(Runnable)並與Runnable中的JList進行交互。完全閱讀http://download.oracle.com/javase/tutorial/uiswing/concurrency/index.html,你就會明白。 – Gili

+0

好的,謝謝你,讀它。 – user863550