温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java如何实现聊天室界面

发布时间:2022-05-20 11:24:46 来源:亿速云 阅读:171 作者:iii 栏目:开发技术

这篇“Java如何实现聊天室界面”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Java如何实现聊天室界面”文章吧。

服务器端:

package Server;
 
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JList;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
 
public class ServerFrame extends JFrame implements ActionListener {
 
    private JButton jbt_start;
    private JButton jbt_stop;
    private JButton jbt_exit;
    private JTextArea jta_disMess;
    private JList jlt_disUsers;
 
    private Server server;
 
    public List<String> online_usernames;
    public List<Integer> online_usernameids;
 
    public ServerFrame(Server server) {
        this.server = server;
        online_usernames = new ArrayList<String>();
        online_usernameids = new ArrayList<Integer>();
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        setTitle("\u670D\u52A1\u5668");
        setIconImage(Toolkit.getDefaultToolkit().getImage("Images/socket.jpg"));
        setSize(449, 301);
        setResizable(false);
        WinCenter.center(this);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent arg0) {
                jbt_exit.doClick();
            }
        });
        getContentPane().setLayout(null);
 
        jbt_start = new JButton("\u542F\u52A8\u670D\u52A1\u5668");
        jbt_start.setBounds(32, 23, 103, 34);
        jbt_start.addActionListener(this);
        getContentPane().add(jbt_start);
 
        jbt_stop = new JButton("\u505C\u6B62\u670D\u52A1\u5668");
        jbt_stop.setBounds(145, 23, 103, 34);
        jbt_stop.setEnabled(false);
        jbt_stop.addActionListener(this);
        getContentPane().add(jbt_stop);
 
        jbt_exit = new JButton("\u9000\u51FA\u670D\u52A1\u5668");
        jbt_exit.setBounds(258, 23, 103, 34);
        jbt_exit.addActionListener(this);
        getContentPane().add(jbt_exit);
 
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(10, 64, 221, 192);
        scrollPane.setWheelScrollingEnabled(true);
        scrollPane.setBorder(BorderFactory.createTitledBorder("聊天消息"));
        getContentPane().add(scrollPane);
 
        jta_disMess = new JTextArea();
        scrollPane.setViewportView(jta_disMess);
 
        JScrollPane scrollPane_1 = new JScrollPane();
        scrollPane_1.setBounds(258, 65, 157, 191);
        scrollPane_1.setBorder(BorderFactory.createTitledBorder("在线用户"));
        getContentPane().add(scrollPane_1);
 
        jlt_disUsers = new JList();
        jlt_disUsers.setVisibleRowCount(4);
        scrollPane_1.setViewportView(jlt_disUsers);
    }
 
    /**
     *
     */
    private static final long serialVersionUID = 1L;
 
    @Override
    public void actionPerformed(ActionEvent arg0) {
        if (arg0.getSource() == jbt_start) {
            jbt_start.setEnabled(false);
            jbt_stop.setEnabled(true);
            server.startServer();
        }
        if (arg0.getSource() == jbt_stop) {
            int flag = JOptionPane.showConfirmDialog(this, "是否要停止服务器?", "",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (flag == JOptionPane.OK_OPTION) {
                server.stopServer();
                jbt_start.setEnabled(true);
                jbt_stop.setEnabled(false);
            }
        }
        if (arg0.getSource() == jbt_exit) {
            if (jbt_stop.isEnabled()) {
                jbt_stop.doClick();
            }
            server.close();
        }
    }
 
    public void setDisUsers(String userNames) {
        if (userNames.equals("@userlist")) {
            jlt_disUsers.removeAll();
            String[] user_null = new String[]{};
            jlt_disUsers.setListData(user_null);
        } else {
            if (userNames.contains("@userlist")) {
                String[] dis = userNames.split("@userlist");
                String[] disUsernames = new String[dis.length / 2];
                int j = 0;
                for (int i = 0; i < dis.length; i++) {
                    disUsernames[j++] = dis[i++];
                }
                jlt_disUsers.removeAll();
                jlt_disUsers.setListData(disUsernames);
            }
            if (userNames.contains("@exit")) {
                String[] dis = {};
                jlt_disUsers.setListData(dis);
            }
        }
    }
 
    public void setDisMess(String message) {
        if (message.contains("@chat")) {
            int local = message.indexOf("@chat");
            jta_disMess.append(message.substring(0, local) + "\n");
            jta_disMess.setCaretPosition(jta_disMess.getText().length());
        }
        if (message.contains("@exit")) {
            jta_disMess.setText("");
        }
    }
 
    public void setStartAndStopUnable() {
        JOptionPane.showMessageDialog(this, "不能同时开启两个服务器");
        jbt_start.setEnabled(false);
        jbt_stop.setEnabled(false);
    }
}

设置窗口居中代码:

package Server;
 
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
 
public class WinCenter {
    public static void center(Window win) {
        Toolkit tkit = Toolkit.getDefaultToolkit();
        Dimension sSize = tkit.getScreenSize();
        Dimension wSize = win.getSize();
        if (wSize.height > sSize.height) {
            wSize.height = sSize.height;
        }
        if (wSize.width > sSize.width) {
            wSize.width = sSize.width;
        }
        win.setLocation((sSize.width - wSize.width) / 2, (sSize.height - wSize.height) / 2);
    }
}

客户端:

登录界面

package Client;
 
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
 
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.Inet4Address;
import java.net.UnknownHostException;
 
import javax.swing.JTextField;
import javax.swing.JButton;
 
public class Client_enterFrame extends JFrame implements ActionListener, KeyListener {
    public Client_enterFrame(Client client) {
        this.client = client;
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        } catch (UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }
        setIconImage(Toolkit.getDefaultToolkit().getImage("Images/socket.jpg"));
        setTitle("\u804A\u5929\u5BA4");
        getContentPane().setLayout(null);
        setSize(296, 249);
        WinCenter.center(this);
        setResizable(false);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                jbt_exit.doClick();
            }
        });
 
        JLabel lblNewLabel = new JLabel("\u7528\u6237\u540D");
        lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 14));
        lblNewLabel.setBounds(23, 30, 81, 34);
        getContentPane().add(lblNewLabel);
 
        jtf_username = new JTextField();
        jtf_username.addKeyListener(this);
        jtf_username.setBounds(114, 30, 143, 34);
        getContentPane().add(jtf_username);
        jtf_username.setColumns(10);
 
        JLabel lblNewLabel_1 = new JLabel("\u670D\u52A1\u5668\u5730\u5740");
        lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 14));
        lblNewLabel_1.setBounds(23, 74, 81, 34);
        getContentPane().add(lblNewLabel_1);
 
        jtf_hostIp = new JTextField();
        jtf_hostIp.setBounds(114, 74, 143, 34);
        jtf_hostIp.addKeyListener(this);
        getContentPane().add(jtf_hostIp);
        try {
            String ip = (String) Inet4Address.getLocalHost().getHostAddress();
            jtf_hostIp.setText(ip);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        jtf_hostIp.setColumns(10);
 
        JLabel lblNewLabel_2 = new JLabel("\u7AEF\u53E3\u53F7");
        lblNewLabel_2.setFont(new Font("宋体", Font.PLAIN, 14));
        lblNewLabel_2.setBounds(23, 118, 81, 34);
        getContentPane().add(lblNewLabel_2);
 
        jtf_hostPort = new JTextField();
        jtf_hostPort.addKeyListener(this);
        jtf_hostPort.setBounds(114, 118, 143, 34);
        getContentPane().add(jtf_hostPort);
        jtf_hostPort.setText("5000");
        jtf_hostPort.setColumns(10);
 
        jbt_enter = new JButton("\u8FDB\u5165\u804A\u5929\u5BA4");
        jbt_enter.addActionListener(this);
        jbt_enter.addKeyListener(this);
        jbt_enter.setFont(new Font("宋体", Font.PLAIN, 14));
        jbt_enter.setBounds(23, 162, 108, 39);
        getContentPane().add(jbt_enter);
 
        jbt_exit = new JButton("\u9000\u51FA\u804A\u5929\u5BA4");
        jbt_exit.setFont(new Font("宋体", Font.PLAIN, 14));
        jbt_exit.setBounds(144, 162, 113, 39);
        jbt_exit.addActionListener(this);
        getContentPane().add(jbt_exit);
    }
 
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private JTextField jtf_username;
    private JTextField jtf_hostIp;
    private JTextField jtf_hostPort;
    private JButton jbt_enter;
    private JButton jbt_exit;
    private Client client;
 
 
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jbt_exit) {
            setVisible(false);
            client.exitLogin();
        }
        if (e.getSource() == jbt_enter) {
            String username = jtf_username.getText();
            username.trim();
            String hostIp = jtf_hostIp.getText();
            hostIp.trim();
            String hostPort = jtf_hostPort.getText();
            hostPort.trim();
            if (!username.equals("")) {
                if (!hostIp.equals("")) {
                    if (!hostPort.equals("")) {
                        String login_mess = client.login(username, hostIp, hostPort);
                        if (login_mess.equals("true")) {
                            this.setVisible(false);
                            client.showChatFrame(username);
                        } else {
                            JOptionPane.showMessageDialog(this, login_mess);
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "服务器连接端口号不能为空!");
                    }
                } else {
                    JOptionPane.showMessageDialog(this, "服务器地址不能为空!");
                }
            } else {
                JOptionPane.showMessageDialog(this, "用户名不能为空!");
            }
        }
    }
 
    @Override
    public void keyPressed(KeyEvent arg0) {
        if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
            jbt_enter.doClick();
        }
    }
 
    @Override
    public void keyReleased(KeyEvent arg0) {
    }
 
    @Override
    public void keyTyped(KeyEvent arg0) {
    }
}

聊天主界面

package Client;
 
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
 
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
 
public class Client_chatFrame extends JFrame implements ActionListener,
        KeyListener, ListSelectionListener {
    public Client_chatFrame(Client client, String title) {
        this.client = client;
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        setIconImage(Toolkit.getDefaultToolkit().getImage("Images/socket.jpg"));
        setTitle("\u804A\u5929\u5BA4" + "  " + title);
        setSize(450, 325);
        WinCenter.center(this);
        setResizable(false);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent arg0) {
                jbt_exit.doClick();
            }
        });
        getContentPane().setLayout(null);
 
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBorder(BorderFactory.createTitledBorder("聊天消息"));
        scrollPane.setBounds(10, 10, 283, 167);
        scrollPane.setWheelScrollingEnabled(true);
        getContentPane().add(scrollPane);
 
        jta_disMess = new JTextArea();
        jta_disMess.setEditable(false);
        scrollPane.setViewportView(jta_disMess);
 
        jtf_inputMess = new JTextField();
        jtf_inputMess.addKeyListener(this);
        jtf_inputMess.setBounds(10, 242, 192, 32);
        getContentPane().add(jtf_inputMess);
        jtf_inputMess.setColumns(10);
 
        jbt_trans = new JButton("\u53D1  \u9001");
        jbt_trans.setFont(new Font("宋体", Font.PLAIN, 14));
        jbt_trans.setBounds(212, 241, 93, 32);
        jbt_trans.addActionListener(this);
        getContentPane().add(jbt_trans);
 
        jbt_clear = new JButton("\u6E05\u9664\u804A\u5929\u8BB0\u5F55");
        jbt_clear.setFont(new Font("宋体", Font.PLAIN, 14));
        jbt_clear.setBounds(158, 187, 135, 37);
        jbt_clear.addActionListener(this);
        getContentPane().add(jbt_clear);
 
        jbt_exit = new JButton("\u9000\u51FA\u804A\u5929\u5BA4");
        jbt_exit.setFont(new Font("宋体", Font.PLAIN, 14));
        jbt_exit.setBounds(20, 189, 128, 37);
        jbt_exit.addActionListener(this);
        getContentPane().add(jbt_exit);
 
        scrollPane_1 = new JScrollPane();
        scrollPane_1.setBorder(BorderFactory.createTitledBorder("在线用户"));
        scrollPane_1.setBounds(303, 10, 128, 214);
        getContentPane().add(scrollPane_1);
 
        jlt_disUsers = new JList();
        jlt_disUsers.setVisibleRowCount(4);
        jlt_disUsers.setSelectedIndex(0);
        jlt_disUsers
                .setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jlt_disUsers.addListSelectionListener(this);
        scrollPane_1.setViewportView(jlt_disUsers);
 
        jbt_singlChat = new JButton("\u5355\u4EBA\u804A\u5929");
        jbt_singlChat.setBounds(315, 241, 116, 32);
        jbt_singlChat.addActionListener(this);
        getContentPane().add(jbt_singlChat);
    }
 
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private JTextField jtf_inputMess;
    private JTextArea jta_disMess;
    private JButton jbt_trans;
    private JButton jbt_clear;
    private JButton jbt_exit;
    private JList jlt_disUsers;
    private JButton jbt_singlChat;
    private JScrollPane scrollPane_1;
    private Client client;
 
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jbt_clear) {
            jta_disMess.setText("");
        }
        if (e.getSource() == jbt_trans) {
            String mess = jtf_inputMess.getText();
            mess.trim();
            jtf_inputMess.setText("");
            if (mess.equals("")) {
                JOptionPane.showMessageDialog(this, "不能发送空消息");
                jtf_inputMess.setText("");
            } else {
                client.transMess(mess);
            }
        }
        if (e.getSource() == jbt_exit) {
            if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(this,
                    "是否确定要退出聊天室?", "提示", JOptionPane.OK_CANCEL_OPTION)) {
                this.setVisible(false);
                client.exitChat();
                System.exit(0);
            }
        }
        if (e.getSource() == jbt_singlChat) {
            String user_names = (String) jlt_disUsers.getSelectedValue();
            if (user_names == null) {
                JOptionPane.showMessageDialog(this, "您未选择聊天对象\n请选择要单独聊天的对象");
            } else {
                if (!client.c_singleFrames.containsKey(user_names)) {
                    createSingleChatFrame(user_names);
                } else {
                    client.c_singleFrames.get(user_names)
                            .setFocusableWindowState(true);
                }
            }
        }
    }
 
    @Override
    public void keyPressed(KeyEvent arg0) {
        if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
            if (arg0.getSource() == jtf_inputMess) {
                jbt_trans.doClick();
            }
        }
    }
 
    @Override
    public void keyReleased(KeyEvent arg0) {
    }
 
    @Override
    public void keyTyped(KeyEvent arg0) {
    }
 
    public void setDisMess(String substring) {
        int local = substring.indexOf("@chat");
        jta_disMess.append(substring.substring(0, local) + "\n");
        jta_disMess.setCaretPosition(jta_disMess.getText().length());
    }
 
    public void setDisUsers(String chat_re) {
        String[] infos = chat_re.split("@userlist");
        String[] info = new String[infos.length / 2];
        for (int i = 1; i < infos.length; i++) {
            int id_user = 0;
            try {
                id_user = Integer.parseInt(infos[i]);
                if (client.getThreadID() == id_user) {
                    if (!client.username.equals(infos[i - 1])) {
                        JOptionPane.showMessageDialog(this,
                                "由于有同名的用户登录,所以您的用户名后面加上了编号");
                        client.username = infos[i - 1];
                        this.setTitle("聊天室    " + client.username);
                        break;
                    } else {
                        break;
                    }
                } else {
                    i++;
                }
            } catch (Exception e) {
            }
        }
        if (infos.length == 2) {
            String[] s = new String[]{};
            if (!client.c_singleFrames.isEmpty()) {
                ListModel list = jlt_disUsers.getModel();
                for (int i = 0; i < list.getSize(); i++) {
                    if (client.c_singleFrames.get(list.getElementAt(i)) != null) {
                        client.c_singleFrames.get(list.getElementAt(i))
                                .setExitNotify();
                    }
                }
            }
            jlt_disUsers.removeAll();
            jlt_disUsers.setListData(s);
        } else {
            if ((infos.length / 2 - 1) < client.username_online.size()) {
                // 有人下线
                List<String> rec = new ArrayList<String>();
                int i = 0;
                for (; i < infos.length; i++) {
                    rec.add(0, infos[i++]);
                }
                for (i = 0; i < client.username_online.size(); i++) {
                    if (!rec.contains(client.username_online.get(i))) {
                        break;
                    }
                }
                String name = client.username_online.get(i);
                client.username_online.remove(i);
                try {
                    client.clientuserid.remove(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
 
                if (client.c_singleFrames.containsKey(name)) {
                    client.c_singleFrames.get(name).closeSingleFrame();
                    client.c_singleFrames.remove(name);
                }
            } else {
                List<Integer> online = new ArrayList<Integer>();
                for (int i = 0; i < client.username_online.size(); i++) {
                    online.add(0, client.clientuserid.get(i));
                }
                if (online.isEmpty()) {
                    for (int i = 1; i < infos.length; i++) {
                        if ((int) Integer.parseInt(infos[i]) != client
                                .getThreadID()) {
                            client.username_online.add(0, infos[i - 1]);
                            client.clientuserid.add(0,
                                    Integer.parseInt(infos[i]));
                        }
                        i++;
                    }
                } else {
                    for (int i = 1; i < infos.length; i++) {
                        if (Integer.parseInt(infos[i]) != client.getThreadID()) {
                            if (!online.contains(Integer.parseInt(infos[i]))) {
                                client.username_online.add(0, infos[i - 1]);
                                client.clientuserid.add(0,
                                        Integer.parseInt(infos[i]));
                            } else {
                                String name = client.username_online
                                        .get(client.clientuserid
                                                .indexOf(Integer
                                                        .parseInt(infos[i])));
                                if (!name.equals(infos[i - 1])) {
                                    if (client.c_singleFrames.containsKey(name)) {
                                        Client_singleFrame cf = client.c_singleFrames
                                                .get(name);
                                        cf.setTitle(name);
                                        client.c_singleFrames.remove(name);
                                        client.c_singleFrames.put(name, cf);
                                        cf.setVisible(false);
 
                                    }
                                    client.username_online.remove(name);
                                    client.clientuserid.remove(new Integer(
                                            Integer.parseInt(infos[i])));
                                    client.username_online.add(0, infos[i - 1]);
                                    client.clientuserid.add(0,
                                            Integer.parseInt(infos[i]));
                                }
                            }
                        }
                        i++;
                    }
                }
 
            }
            try {
                for (int i = 0; i < client.username_online.size(); i++) {
                    info[i] = client.username_online.get(i);
                }
 
            } catch (Exception e) {
            }
            jlt_disUsers.removeAll();
            jlt_disUsers.setListData(info);
        }
    }
 
    public void closeClient() {
        JOptionPane.showMessageDialog(this, "服务器已关闭", "提示",
                JOptionPane.OK_OPTION);
        client.exitClient();
        setVisible(false);
    }
 
    @Override
    public void valueChanged(ListSelectionEvent e) {
        if (e.getSource() == jlt_disUsers) {
        }
    }
 
    public void createSingleChatFrame(String name) {
        Client_singleFrame c_singlFrame = new Client_singleFrame(client, name);
        client.c_singleFrames.put(name, c_singlFrame);
        try {
            c_singlFrame.userThreadID = client.clientuserid
                    .get(client.username_online.indexOf(name));
        } catch (Exception e) {
        }
 
        c_singlFrame.setVisible(true);
    }
 
    public void setSingleFrame(String chat_re) {
        String[] infos = chat_re.split("@single");
        try {
            if (client.c_singleFrames.containsKey(infos[0])) {
                client.c_singleFrames.get(infos[0]).setDisMess(infos[3]);
            } else {
                createSingleChatFrame(infos[0]);
                client.c_singleFrames.get(infos[0]).setDisMess(infos[3]);
            }
        } catch (Exception e) {
        }
    }
}

单人聊天界面

package Client;
 
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
 
public class Client_singleFrame extends JFrame implements ActionListener, KeyListener {
 
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private static JTextArea jta_disMess;
    private JTextField jtf_inputMess;
    private JButton jbt_trans;
 
    public int userThreadID = 0;
 
    private Client client;
 
    public Client_singleFrame(Client client, String title) {
        this.client = client;
        init(title);
    }
 
    private void init(String title) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        } catch (UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }
        setIconImage(Toolkit.getDefaultToolkit().getImage("Images/socket.jpg"));
        WinCenter.center(this);
        setTitle(title);
        setSize(400, 400);
        setResizable(false);
        setContentPane(createContentPanel());
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                closeSingleFrame();
            }
        });
    }
 
    private Container createContentPanel() {
        JPanel jp = new JPanel();
        jp.setBorder(BorderFactory.createTitledBorder("聊天消息"));
        jp.setLayout(new BorderLayout());
        jta_disMess = new JTextArea();
        jta_disMess.setEditable(false);
        jp.add(BorderLayout.CENTER, new JScrollPane(jta_disMess));
        jp.add(BorderLayout.SOUTH, createInput());
        return jp;
    }
 
    private Component createInput() {
        JPanel jp = new JPanel();
        jp.setBorder(BorderFactory.createTitledBorder("发送消息"));
        jp.setLayout(new BorderLayout());
        jtf_inputMess = new JTextField();
        jtf_inputMess.addKeyListener(this);
        jbt_trans = new JButton("发送");
        jbt_trans.addActionListener(this);
        jp.add(jtf_inputMess, BorderLayout.CENTER);
        jp.add(jbt_trans, BorderLayout.EAST);
        return jp;
    }
 
    @Override
    public void keyPressed(KeyEvent arg0) {
        if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
            if (arg0.getSource() == jtf_inputMess) {
                jbt_trans.doClick();
            }
        }
    }
 
    @Override
    public void keyReleased(KeyEvent arg0) {
    }
 
    @Override
    public void keyTyped(KeyEvent arg0) {
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jbt_trans) {
            String str = jtf_inputMess.getText();
            str.trim();
            jtf_inputMess.setText("");
            if (str.equals("")) {
                JOptionPane.showMessageDialog(this, "信息不能为空");
            } else {
                SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd  HH:mm");
                String date = form.format(new Date());
                String mess = client.username + "  " + date + "\n" + str;
                jta_disMess.append(mess + "\n");
                jta_disMess.setCaretPosition(jta_disMess.getText().length());
                int index = client.username_online.indexOf(this.getTitle());
                String info = client.username + "@single" + client.getThreadID() + "@single" +
                        (int) client.clientuserid.get(index) + "@single" +
                        mess + "@single";
                try {
                    client.dos.writeUTF(info);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
 
    public void setDisMess(String chat_re) {
        jta_disMess.append(chat_re + "\n");
        jta_disMess.setCaretPosition(jta_disMess.getText().length());
    }
 
    public void closeSingleFrame() {
        client.c_singleFrames.remove(this.getTitle());
        setVisible(false);
    }
 
    public void setExitNotify() {
        jta_disMess.append(this.getTitle() + "已下线.....");
        jbt_trans.setEnabled(false);
    }
}

设置窗体居中

package Client;
 
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
 
public class WinCenter {
    public static void center(Window win) {
        Toolkit tkit = Toolkit.getDefaultToolkit();
        Dimension sSize = tkit.getScreenSize();
        Dimension wSize = win.getSize();
        if (wSize.height > sSize.height) {
            wSize.height = sSize.height;
        }
        if (wSize.width > sSize.width) {
            wSize.width = sSize.width;
        }
        win.setLocation((sSize.width - wSize.width) / 2, (sSize.height - wSize.height) / 2);
    }
}

以上就是关于“Java如何实现聊天室界面”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI