以图形用户界面的形式完成Java即使聊天程序设计:可通过输入IP地址,端口号进行客户端服务器连接,连接以后可以发送文字,图片等信息,具体功能可以仿照qq

时间: 2024-03-07 13:53:39 浏览: 25
下面是一个基于Java图形用户界面的即时聊天程序设计,可以通过输入IP地址和端口号进行客户端服务器连接,连接后可以发送文字和图片等信息,界面类似于QQ: ```java import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import javax.swing.filechooser.FileNameExtensionFilter; public class ChatUI extends JFrame implements ActionListener, Runnable { private JTextField messageField; private JTextArea messageArea; private JButton sendButton; private JButton imageButton; private JLabel statusLabel; private Socket socket; private DataInputStream inputStream; private DataOutputStream outputStream; public ChatUI() { setTitle("Chat Application"); setSize(600, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // 创建组件 messageField = new JTextField(30); messageArea = new JTextArea(); JScrollPane scrollPane = new JScrollPane(messageArea); sendButton = new JButton("Send"); imageButton = new JButton("Image"); statusLabel = new JLabel("Not connected"); // 添加组件 JPanel panel = new JPanel(new BorderLayout()); panel.add(messageField, BorderLayout.CENTER); panel.add(sendButton, BorderLayout.EAST); panel.add(imageButton, BorderLayout.WEST); add(scrollPane, BorderLayout.CENTER); add(panel, BorderLayout.SOUTH); add(statusLabel, BorderLayout.NORTH); // 添加事件监听器 messageField.addActionListener(this); sendButton.addActionListener(this); imageButton.addActionListener(this); setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == sendButton || e.getSource() == messageField) { String message = messageField.getText(); if (!message.isEmpty()) { try { outputStream.writeUTF(message); messageArea.append("You: " + message + "\n"); messageField.setText(""); } catch (IOException ex) { statusLabel.setText("Error: " + ex.getMessage()); } } } else if (e.getSource() == imageButton) { JFileChooser fileChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "jpeg", "png", "gif"); fileChooser.setFileFilter(filter); int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[fis.available()]; fis.read(buffer); outputStream.write(buffer); messageArea.append("You sent an image: " + file.getName() + "\n"); } catch (IOException ex) { statusLabel.setText("Error: " + ex.getMessage()); } } } } public void run() { try { socket = new Socket("localhost", 1234); inputStream = new DataInputStream(socket.getInputStream()); outputStream = new DataOutputStream(socket.getOutputStream()); statusLabel.setText("Connected"); while (true) { String message = inputStream.readUTF(); if (message.startsWith("IMAGE:")) { int length = Integer.parseInt(message.substring(6)); byte[] buffer = new byte[length]; inputStream.readFully(buffer); ImageIcon imageIcon = new ImageIcon(buffer); messageArea.append("Peer sent an image: " + imageIcon.getDescription() + "\n"); JLabel imageLabel = new JLabel(imageIcon); JOptionPane.showMessageDialog(this, imageLabel, "Received Image", JOptionPane.PLAIN_MESSAGE); } else { messageArea.append("Peer: " + message + "\n"); } } } catch (IOException ex) { statusLabel.setText("Error: " + ex.getMessage()); } finally { try { if (socket != null) socket.close(); if (inputStream != null) inputStream.close(); if (outputStream != null) outputStream.close(); } catch (IOException ex) { statusLabel.setText("Error: " + ex.getMessage()); } } } public static void main(String[] args) { ChatUI chatUI = new ChatUI(); Thread thread = new Thread(chatUI); thread.start(); } } ``` 在这个例子中,我们创建了一个继承自JFrame的ChatUI类,并在构造函数中设置了标题,大小,关闭操作和位置。我们使用JTextField来让用户输入聊天消息,使用JTextArea来显示聊天记录,并使用JScrollPane添加滚动条功能。我们还创建了一个发送按钮和一个图片按钮,并使用JLabel显示当前连接状态。 我们将这些组件添加到JFrame中,并使用BorderLayout管理它们的位置。我们还添加了事件监听器,以便在用户输入聊天消息并单击发送按钮或按回车键时,将消息添加到聊天记录中。我们还添加了一个事件监听器,以便在用户单击图片按钮时,选择并发送图片。 我们还实现了Runnable接口,并在run方法中创建了一个Socket对象,并使用DataInputStream和DataOutputStream进行通信。我们使用while循环来接收来自服务器的消息,并在JTextArea中显示它们。如果接收到的消息以"IMAGE:"开头,则说明接收到的是图片,我们使用JOptionPane显示它。 当运行该程序时,将显示一个聊天窗口,用户可以在其中输入和发送聊天消息和图片,并且可以通过输入IP地址和端口号进行客户端服务器连接,界面类似于QQ。

相关推荐

最新推荐

recommend-type

java编程实现获取服务器IP地址及MAC地址的方法

主要介绍了java编程实现获取机器IP地址及MAC地址的方法,实例分析了Java分别针对单网卡及多网卡的情况下获取服务器IP地址与MAC地址的相关技巧,需要的朋友可以参考下
recommend-type

JAVA如何获取客户端IP地址和MAC地址

本篇文章主要介绍了JAVA如何获取客户端IP地址和MAC地址非常具有实用价值,这里整理了详细的代码,需要的朋友可以参考下
recommend-type

Java获取服务器IP及端口的方法实例分析

主要介绍了Java获取服务器IP及端口的方法,结合实例形式分析了java针对客户端及服务器端各种常见的信息操作技巧与注意事项,需要的朋友可以参考下
recommend-type

javascript连接mysql与php通过odbc连接任意数据库的实例

1、javascript连接mysql使用的是”new ActiveXObject“这个对象,这个对象只有IE浏览器支持,所以只能在IE浏览器下实现连接mysql。 2、javascript也是通过odbc连接mysql,和php不同的是,其中一个参数,图片中,...
recommend-type

java获取linux服务器上的IP操作

主要介绍了java获取linux服务器上的IP操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。