Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement chat room interface with Java

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "Java how to achieve chat room interface", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can gain something after reading this article. Let's take a look at this "how to achieve chat room interface in Java" article.

Server side: 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 online_usernames; public List online_usernameids; public ServerFrame (Server server) {this.server = server; online_usernames = new ArrayList (); online_usernameids = new ArrayList () 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 (chat message)); 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, "do you want to stop the server?" , ", 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 >

< 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 rec = new ArrayList(); 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 online = new ArrayList(); 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) }} the above is the content of this article on "how to implement chat room interface in Java". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report