如何在java Chat中更新JList

发布于 2024-12-01 12:01:34 字数 10688 浏览 0 评论 0原文

抱歉,我这里遇到了问题,相信我,我已经尽力了。但不幸的是,在考虑发帖寻求帮助之前,我无法收回它。提前感谢您付出的时间和精力。

我正在尝试更新我的客户端 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();
    }
 }

I am sorry, I have a problem here, believe me I have tried as much as I can. But unfortunately couldn't get the back of it, before thinking of posting for help. And thank you in advance for your time and effort.

I am trying to update my Client JList (userList) so that when a new client comes in, the initial client would be updated. but at present, when there's a single client, it can see itself but when another client enters the chat, only that client sees the two clients connected, the initial client is not updated with the name on the JList.
Please help simplify any answer because I am not expert in Java. Thank you!

The ClientChat Code:

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

The ServerChat code:

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

The ServerThread code:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

躲猫猫 2024-12-08 12:01:34

您对Swing 中的并发有真正的问题,所有输出BackGround Tasks 必须包装到 invokeLater() 中,如果您在这里等待可能且重复的网络故障,那么最好将其包装到 invokeAndWait() 中

1) 仅创建一种方法,用于将字符串添加/附加到 JTextArea

2) 方法将字符串添加/附加到 JTextArea 包装到 invokeLater()

3) 检查这个 线程并通过给定示例修改/更改所有方法

you have real problem with Concurency in Swing, all output from BackGround Tasks must be wrapperd into invokeLater(), if you here awaiting possible and repeated networks fault(s) then better would be into invokeAndWait()

1) create only one method for add/appends String to the JTextArea

2) method add/appends String to the JTextArea wrap into invokeLater()

3) check this thread and amend/change all methods by given example

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文