版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
第Java聊天室之实现聊天室客户端功能privateSocketsocket;
privatebooleanloginFlag=false;//为true时表示已经登录,为false时表示未登录
publicstaticvoidmain(Stringargs[]){
System.out.println(SwingUtilities.isEventDispatchThread());
EventQueue.invokeLater(newRunnable(){
publicvoidrun(){
System.out.println(SwingUtilities.isEventDispatchThread());
try{
ChatClientFrameframe=newChatClientFrame();
frame.setVisible(true);
frame.createClientSocket();//调用方法创建套接字对象
}catch(Exceptione){
e.printStackTrace();
publicvoidcreateClientSocket(){
try{
socket=newSocket("127.0.0.1",9527);//创建套接字对象
out=newObjectOutputStream(socket.getOutputStream());//创建输出流对象
SwingWorkerVoid,Voidworker=newSwingWorkerVoid,Void(){
@Override
protectedVoiddoInBackground()throwsException{
try{
System.out.println(SwingUtilities.isEventDispatchThread());
BufferedReaderin=newBufferedReader(newInputStreamReader(
socket.getInputStream()));//创建输入流对象
DefaultComboBoxModelmodel=(DefaultComboBoxModel)user_list
.getModel();//获得列表框的模型
while(true){
Stringinfo=in.readLine().trim();//读取信息
if(!info.startsWith("MSG:")){//接收到的不是消息
if(info.startsWith("退出:")){//接收到的是退出消息
model.removeElement(info.substring(3));//从用户列表中移除用户
}else{//接收到的是登录用户
booleanitemFlag=false;//标记是否为列表框添加列表项,为true不添加,为false添加
for(inti=0;imodel.getSize();i++){//对用户列表进行遍历
if(info.equals((String)model.getElementAt(i))){//如果用户列表中存在该用户名
itemFlag=true;//设置为true,表示不添加到用户列表
break;//结束for循环
if(!itemFlag){
model.addElement(info);//将登录用户添加到用户列表
}else{//如果获得的是消息,则在文本域中显示接收到的消息
DateFormatdf=DateFormat.getDateInstance();//获得DateFormat实例
StringdateString=df.format(newDate());//格式化为日期
df=DateFormat.getTimeInstance(DateFormat.MEDIUM);//获得DateFormat实例
StringtimeString=df.format(newDate());//格式化为时间
StringsendUser=info.substring(4,info.indexOf(":发送给:"));//获得发送信息的用户
StringreceiveInfo=info.substring(info.indexOf(":的信息是:")+6);//获得接收到的信息
ta_info.append(""+sendUser+""+dateString+""+timeString+"\n"+receiveInfo+"\n");//在文本域中显示信息
ta_info.setSelectionStart(ta_info.getText().length()-1);//设置选择起始位置
ta_info.setSelectionEnd(ta_info.getText().length());//设置选择的结束位置
tf_send.requestFocus();//使发送信息文本框获得焦点
}catch(IOExceptione){
e.printStackTrace();
returnnull;
worker.execute();
//newClientThread(socket).start();//创建并启动线程对象
}catch(UnknownHostExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
classClientThreadextendsThread{
Socketsocket;
publicClientThread(Socketsocket){
this.socket=socket;
publicvoidrun(){
privatevoidsend(){
if(!loginFlag){
JOptionPane.showMessageDialog(null,"请先登录。");
return;//如果用户没登录则返回
StringsendUserName=tf_newUser.getText().trim();//获得登录用户名
Stringinfo=tf_send.getText();//获得输入的发送信息
if(info.equals("")){
return;//如果没输入信息则返回,即不发送
VectorStringv=newVectorString//创建向量对象,用于存储发送的消息
Object[]receiveUserNames=user_list.getSelectedValues();//获得选择的用户数组
if(receiveUserNames.length=0){
return;//如果没选择用户则返回
for(inti=0;ireceiveUserNames.length;i++){
Stringmsg=sendUserName+":发送给:"+(String)receiveUserNames[i]
+":的信息是:"+info;//定义发送的信息
v.add(msg);//将信息添加到向量
try{
out.writeObject(v);//将向量写入输出流,完成信息的发送
out.flush();//刷新输出缓冲区
}catch(IOExceptione){
e.printStackTrace();
DateFormatdf=DateFormat.getDateInstance();//获得DateFormat实例
StringdateString=df.format(newDate());//格式化为日期
df=DateFormat.getTimeInstance(DateFormat.MEDIUM);//获得DateFormat实例
StringtimeString=df.format(newDate());//格式化为时间
StringsendUser=tf_newUser.getText().trim();//获得发送信息的用户
StringreceiveInfo=tf_send.getText().trim();//显示发送的信息
ta_info.append(""+sendUser+""+dateString+""+timeString+"\n"+receiveInfo+"\n");//在文本域中显示信息
tf_send.setText(null);//清空文本框
ta_info.setSelectionStart(ta_info.getText().length()-1);//设置选择的起始位置
ta_info.setSelectionEnd(ta_info.getText().length());//设置选择的结束位置
tf_send.requestFocus();//使发送信息文本框获得焦点
*Createtheframe
publicChatClientFrame(){
super();
setTitle("聊天室客户端");
setBounds(100,100,385,288);
finalJPanelpanel=newJPanel();
getContentPane().add(panel,BorderLayout.SOUTH);
finalJLabellabel=newJLabel();
label.setText("输入聊天内容:");
panel.add(label);
tf_send=newJTextField();
tf_send.addActionListener(newActionListener(){
publicvoidactionPerformed(finalActionEvente){
send();//调用方法发送信息
tf_send.setPreferredSize(newDimension(180,25));
panel.add(tf_send);
finalJButtonbutton=newJButton();
button.addActionListener(newActionListener(){
publicvoidactionPerformed(finalActionEvente){
send();//调用方法发送信息
button.setText("发送");
panel.add(button);
finalJSplitPanesplitPane=newJSplitPane();
splitPane.setDividerLocation(100);
getContentPane().add(splitPane,BorderLayout.CENTER);
finalJScrollPanescrollPane=newJScrollPane();
splitPane.setRightComponent(scrollPane);
ta_info=newJTextArea();
ta_info.setFont(newFont("",Font.BOLD,14));
scrollPane.setViewportView(ta_info);
finalJScrollPanescrollPane_1=newJScrollPane();
splitPane.setLeftComponent(scrollPane_1);
user_list=newJList();
user_list.setModel(newDefaultComboBoxModel(newString[]{""}));
scrollPane_1.setViewportView(user_list);
finalJPanelpanel_1=newJPanel();
getContentPane().add(panel_1,BorderLayout.NORTH);
finalJLabellabel_1=newJLabel();
label_1.setText("用户名称:");
panel_1.add(label_1);
tf_newUser=newJTextField();
tf_newUser.setPreferredSize(newDimension(140,25));
panel_1.add(tf_newUser);
finalJButtonbutton_1=newJButton();
button_1.addActionListener(newActionListener(){
publicvoidactionPerformed(finalActionEvente){
if(loginFlag){//已登录标记为true
JOptionPane.showMessageDialog(null,"在同一窗口只能登录一次。");
return;
StringuserName=tf_newUser.getText().trim();//获得登录用户名
Vectorv=newVector();//定义向量,用于存储登录用户
v.add("用户:"+userName);//添加登录用户
try{
out.writeObject(v);//将用户向量发送到服务器
out.flush();//刷新输出缓冲区
}catch(IOExceptionex){
ex.printStackTrace();
tf_newUser.setEnabled(false);//禁用用户文本框
loginFlag=true;//将已登录标记设置为true
button_1.setText("登录");
panel_1.add(button_1);
finalJButtonbutton_2=newJButton();
button_2.addActionListener(newActionListener(){
publicvoidactionPerformed(finalActionEvente){
StringexitUser=tf_newUser.getText().trim();
Vectorv=newVector();
v.add("退出:"+exitUser);
try{
out.writeObject(v);
out.flush();//刷新输出缓冲区
}catch(IOExceptionex){
ex.printStackTrace();
System.exit(0);//退出系统
button_2.setText("退出");
panel_1.add(button_2);
//托盘
if(SystemTray.isSupported()){//判断是否支持系统托盘
URLurl=ResourceUtil.getResource("client.png",null);//获取图片所在的URL
ImageIconicon=newImageIcon(url);//实例化图像对象
Imageimage=icon.getImage();//获得Image对象
TrayIcontrayIcon=newTrayIcon(image);//创建托盘图标
trayIcon.addMouseListener(newMouseAdapter(){//为托盘添加鼠标适配器
publicvoidmouseClicked(MouseEvente){//鼠标事件
if(e.getClickCount()==2){//判断是否双击了鼠标
showFrame();//调用方法显示窗体
trayIcon.setToolTip("系统托盘");//添加工具提示文本
PopupMenupopupMenu=newPopupMenu();//创建弹出菜单
MenuItemexit=newMenuItem("退出");//创建菜单项
exit.addActionListener(newActionListener(){//添加
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 初三道德与法治中考复习:开放性设问之倡议书、标语与活动方案专项突破教案
- 《装饰工程灯具采购合同实务解析》教案-面向高职工程造价专业二年级
- 2026宁波大美海湾旅游开发有限公司招聘1人笔试模拟试题及答案详解
- 2026山西运城河津市中医医院招聘正式在编人员2人笔试备考试题及答案详解
- 2026西工大化学与化工学院博士后招聘58人笔试备考题库及答案详解
- 建筑施工消防演练方案及流程
- 2026山东滨城区国有企业招聘工作人员13人笔试备考题库及答案详解
- 2026河北石家庄深泽县医共体集团公开招聘工作人员34名笔试模拟试题及答案详解
- 2026三峡陆上新能源总部社会招聘40人(第一批内蒙古)笔试参考题库及答案详解
- 2026浙江金华义乌市稠城街道社区卫生服务中心编外聘用人员招聘4人笔试参考题库及答案详解
- 作文格子纸(小学生专用Word版)
- 八年级地理第三次月考试卷
- 贵州义华实业有限责任公司煤矸石提硫建设项目环评报告
- 个人嘉奖登记(报告)表(无水印)
- 泌乳奶牛营养需要
- 水利工程施工监理规范SL288-2014标准参考
- DL-T 1083-2019 火力发电厂分散控制系统技术条件
- 六三制新青岛版四年级下册科学第16课《动物的“家”》课件
- LY/T 2810-2017结构化森林经营技术规程
- GB/T 14996-2010高温合金冷轧板
- 人工起道捣固作业考评表(工务专业)
评论
0/150
提交评论