Showing preview only (266K chars total). Download the full file or copy to clipboard to get everything.
Repository: sxei/myqq
Branch: master
Commit: e603e4a0027c
Files: 61
Total size: 231.6 KB
Directory structure:
gitextract_tbbip7i2/
├── .classpath
├── .gitignore
├── .project
├── .settings/
│ └── org.eclipse.jdt.core.prefs
├── LICENSE
├── README.md
├── lib/
│ ├── AbsoluteLayout.jar
│ ├── mysql-connector-java-5.0.4-bin.jar
│ └── swing-layout-1.0.3.jar
├── myqq.sql
└── src/
├── client/
│ ├── common/
│ │ ├── ComboBoxRenderer.java
│ │ ├── MyLabel.java
│ │ ├── MyTextPane.java
│ │ └── MyTreeIcon.java
│ ├── control/
│ │ ├── Chat.java
│ │ ├── Login.java
│ │ ├── Main.java
│ │ ├── MyTree.java
│ │ ├── QunChat.java
│ │ ├── RecieveThread.java
│ │ ├── Register.java
│ │ └── SendTread.java
│ ├── frame/
│ │ ├── ChatFrame.form
│ │ ├── ChatFrame.java
│ │ ├── FaceFrame.java
│ │ ├── LoginFrame.java
│ │ ├── MainFrame.java
│ │ ├── MyPanel.java
│ │ ├── PublicMessageFrame.java
│ │ ├── QunChatFrame.java
│ │ ├── RegisterFrame.java
│ │ ├── ScreenFram.java
│ │ └── SendFileFrame.java
│ └── socket/
│ ├── CC_TCP.java
│ ├── CS_TCP.java
│ ├── S_TCP.java
│ └── UDPChat.java
├── com/
│ ├── MyTools.java
│ └── socket/
│ ├── TCP.java
│ ├── TCPServer.java
│ └── UDP.java
├── log4j-1.2.dtd
├── log4j.xml
└── server/
├── QQServer.java
├── common/
│ ├── JDBC.java
│ ├── Page.java
│ └── PageService.java
├── dao/
│ ├── IMsg.java
│ ├── IUser.java
│ ├── MsgDao.java
│ └── UserDao.java
├── entity/
│ ├── Msg.java
│ └── Users.java
└── frame/
├── MainWindow.java
├── MsgActionListener.java
├── MsgMana.java
├── ServerActionListen.java
├── ServerMana.java
├── UserActionListen.java
├── UserMana.java
└── UserTableCahnged.java
================================================
FILE CONTENTS
================================================
================================================
FILE: .classpath
================================================
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="lib/AbsoluteLayout.jar"/>
<classpathentry kind="lib" path="lib/mysql-connector-java-5.0.4-bin.jar"/>
<classpathentry kind="lib" path="lib/swing-layout-1.0.3.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>
================================================
FILE: .gitignore
================================================
*.class
bin
================================================
FILE: .project
================================================
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>myqq</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
================================================
FILE: .settings/org.eclipse.jdt.core.prefs
================================================
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.7
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2017 小茗同学
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# 说明
Java版SWing“高”仿QQ即时通聊天系统
原贴地址:http://tieba.baidu.com/p/1933997044
首先说明这是一个很老很老的小项目,还是12年的时候写的,代码真的很low很low,low到什么级别呢?low到很多变量都是用中文命名的!这次之所以重新整理上传到GitHub,是因为12年的时候曾把这个发到网上,然后竟然还有很多人想要代码,当时是上传到CSDN还设置了积分,不方便下载。虽然没什么技术含量,但感觉对新人应该还是有一点借鉴的地方的。
用的是`Oracle`数据库(为方便安装,后来改为`MySQL`),`Swing`作界面。界面上高仿腾讯QQ的(特别是登录窗体,几乎与腾讯QQ2011没有区别 ),包括客户端和服务端,包含创建数据库的SQL命令,目前主要实现的功能包括私聊、表情发送、图片发送、文件传输、截图、群聊天室、系统公告、桌面弹窗、声音提醒、离线消息发送与接收等……

重要说明:
1. 不会继续更新和维护,因为过去很多年了;
2. 本身也有很多bug,仅限拿来玩玩;
3. 代码质量不代表真实水平,毕竟,还是学生时代的作品。
# 安装运行
环境要求:`jdk1.7` + `mysql`。
## 导入数据库
本地新建一个名为`myqq`的数据库,utf-8编码,导入`myqq.sql`即可,其实这里面很简单,就2个表。
## 导入Eclipse
项目是一个JavaSE项目,使用Eclipse3.7开发,按普通项目导入Eclipse即可。如果导入之后有关`sun.audio.AudioPlayer.player`部分报如下错误:
Access restriction: The method start(InputStream) from the type AudioPlayer is not accessible due to restriction on required library D:\GreenSoft\Java\jre7\lib\rt.jar
可以先构建路径移除`JRE System Library`,然后再通过`Add Library`把`JRE System Library`添加回来即可。
## 修改配置
打开`com.MyTools.java`,修改服务器IP(本地测试时就是127.0.0.1)、服务器端口、数据库地址、数据库密码等。
## 启动
首先启动服务端:`server.frame.MainWindow.java`,记得要点击界面上的“启动MyQQ服务器”按钮,然后启动客户端:`client.control.Login.java`,要测试的话可以多启动几个客户端用不同账号测试。
内置的3个测试账号:小茗同学、马化腾、吴阳阳,密码都是`123`。当然也可以自己注册一个。
# 部分截图
主窗体:

发起聊天:

互相聊天:

表情发送:

简单的聊天室:

系统弹窗公告:

进入聊天室:

非常简陋的后台:

================================================
FILE: myqq.sql
================================================
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50505
Source Host : localhost:3306
Source Database : myqq
Target Server Type : MYSQL
Target Server Version : 50505
File Encoding : 65001
Date: 2017-05-10 15:15:06
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `msg`
-- ----------------------------
DROP TABLE IF EXISTS `msg`;
CREATE TABLE `msg` (
`msg_id` int(11) NOT NULL AUTO_INCREMENT,
`msg_content` varchar(2000) DEFAULT NULL,
`msg_sendfrom` int(11) DEFAULT NULL,
`msg_sendto` int(11) DEFAULT NULL,
`msg_sendtime` datetime DEFAULT NULL,
`msg_remark` varchar(3000) DEFAULT NULL,
`msg_type` varchar(10) DEFAULT NULL,
PRIMARY KEY (`msg_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of msg
-- ----------------------------
-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`u_id` int(11) NOT NULL AUTO_INCREMENT,
`u_name` varchar(50) DEFAULT NULL,
`u_pwd` varchar(50) DEFAULT NULL,
`u_ip` varchar(50) DEFAULT NULL,
`u_state` varchar(50) DEFAULT NULL,
`u_gender` varchar(50) DEFAULT NULL,
`u_email` varchar(50) DEFAULT NULL,
`u_last_login` datetime DEFAULT NULL,
`u_last_exit` datetime DEFAULT NULL,
`u_remarke` varchar(3000) DEFAULT NULL,
`u_signature` varchar(100) DEFAULT NULL,
`u_head_img` varchar(100) DEFAULT NULL,
`u_type` varchar(50) DEFAULT NULL,
`u_birthday` date DEFAULT NULL,
PRIMARY KEY (`u_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', '小茗同学', '123', '127.0.0.1', '-1', '男', 'jfs@qq.com', '2017-05-10 14:49:23', '2017-05-10 14:52:22', null, '大家好,我是小茗同学!', '0', null, '1992-07-28');
INSERT INTO `users` VALUES ('2', '马化腾', '123', '127.0.0.1', '-1', '男', 'ss@qq.com', '2017-05-10 14:49:09', '2017-05-10 14:52:25', null, '哈哈,我是马化腾!', '3', null, '1992-07-28');
INSERT INTO `users` VALUES ('3', '吴阳阳', '123', '172.16.4.97', '0', '男', 'fjs@qq.com ', '2015-04-21 18:01:57', null, null, '我与徐婷婷不得不说的事儿', '4', null, '1992-07-28');
================================================
FILE: src/client/common/ComboBoxRenderer.java
================================================
package client.common;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
public class ComboBoxRenderer extends JLabel implements ListCellRenderer
{
private Font uhOhFont;
private ImageIcon[] images=null;
private String[] imageNames=null;
public ComboBoxRenderer(ImageIcon[] images,String[] imageNames)
{
setOpaque(true);
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
this.imageNames=imageNames;
this.images=images;
}
/*
* This method finds the image and text corresponding to the selected value
* and returns the label, set up to display the text and image.
*/
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
{
// Get the selected index. (The index param isn't
// always valid, so just use the value.)
int selectedIndex = ((Integer) value).intValue();
if (isSelected)
{
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else
{
setBackground(list.getBackground());
setForeground(list.getForeground());
}
// Set the icon and text. If icon was null, say so.
ImageIcon icon = images[selectedIndex];
String pet = imageNames[selectedIndex];
setIcon(icon);
if (icon != null)
{
setText(pet);
setFont(list.getFont());
}
else
{
setUhOhText(pet + " (没有有效的图片)", list.getFont());
}
return this;
}
// Set the font and text when no image was found.
protected void setUhOhText(String uhOhText, Font normalFont)
{
if (uhOhFont == null)
{ // lazily create this font
uhOhFont = normalFont.deriveFont(Font.ITALIC);
}
setFont(uhOhFont);
setText(uhOhText);
}
}
================================================
FILE: src/client/common/MyLabel.java
================================================
package client.common;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import com.MyTools;
public class MyLabel
{
//规定:常规状态图片索引为1,鼠标进入为2,鼠标按下为3,鼠标释放还是2
JLabel jLabel=null;
String fileName="";
String extension="";
int mode=1;//模式为1表示用图片,模式为2表示用Boder
Color backColor=null;//Label的父容器的背景色
/**
* 根据指定的若干张图片来实例化一个Label
* @param fileName 图片的路径,不包括图片索引和扩展名,例如
* 如果图片名为img/QQ_1.png,则写成"../img/QQ"
* @param extension 扩展名,不包括前面的点"."
*/
public MyLabel(JLabel jLabel,String fileName,String extension)
{
this.jLabel=jLabel;
this.fileName=fileName;
this.extension=extension;
}
public MyLabel(JLabel jLabel)
{
this.jLabel=jLabel;
this.mode=0;
backColor=this.jLabel.getParent().getBackground();
setEtchedBorder(backColor);//将label的默认边框颜色设置的和背景色一样,以达到不现实边框的作用
}
public MyLabel(JLabel jLabel,Color color)
{
this.jLabel=jLabel;
this.mode=0;
backColor=color;
setEtchedBorder(backColor);
}
/**
* 设置成一种边框,中文翻译作什么我也不知道
* @param color
*/
public void setEtchedBorder(Color color)
{
jLabel.setBorder(javax.swing.BorderFactory.createEtchedBorder(color, color));
}
/**
* 给jLabel添加事件
*/
public void addEvent()
{
jLabel.addMouseListener(new MouseAdapter()
{
@Override
public void mouseEntered(MouseEvent e)
{
if(mode==1)
jLabel.setIcon(MyTools.getIcon(fileName+"_2."+extension));
else
setEtchedBorder(Color.red);
}
@Override
public void mouseExited(MouseEvent e)
{
if(mode==1)
jLabel.setIcon(MyTools.getIcon(fileName+"_1."+extension));
else
setEtchedBorder(backColor);
}
@Override
public void mousePressed(MouseEvent e)
{
if(mode==1)
jLabel.setIcon(MyTools.getIcon(fileName+"_3."+extension));
else
jLabel.setBorder(javax.swing.BorderFactory.createBevelBorder(
javax.swing.border.BevelBorder.LOWERED));
}
@Override
public void mouseReleased(MouseEvent e)
{
if(mode==1)
jLabel.setIcon(MyTools.getIcon(fileName+"_2."+extension));
else
setEtchedBorder(Color.red);
}
});
}
}
================================================
FILE: src/client/common/MyTextPane.java
================================================
package client.common;
import java.awt.Color;
import java.awt.Image;
import java.text.DateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import com.MyTools;
public class MyTextPane
{
JTextPane textPane=null;
StyledDocument document=null;
public MyTextPane(JTextPane textPane)
{
this.textPane=textPane;
document=this.textPane.getStyledDocument();
}
public void addText(String text,SimpleAttributeSet font)
{
try
{
document.insertString(document.getLength(), text, font);
StyleConstants.setIcon(getMyAttribute(), MyTools.getIcon("../img/QQ_64.png"));
}
catch (BadLocationException e)
{
e.printStackTrace();
}
}
public void addIcon(String imagePath,String friendName)
{
try
{
String time= DateFormat.getTimeInstance().format(new Date());
document.insertString(document.getLength(), friendName+" "+time+"\n", MyTextPane.getTimeAttribute());
textPane.setCaretPosition(document.getLength());
textPane.insertIcon(MyTools.getIcon(imagePath));
document.insertString(document.getLength(), "\n", getFriendAttribute());
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 临时写的,以后改进
* @param imagePath
* @param friendName
*/
public void addIcon(Image image,String friendName)
{
try
{
String time= DateFormat.getTimeInstance().format(new Date());
document.insertString(document.getLength(), friendName+" "+time+"\n", MyTextPane.getTimeAttribute());
textPane.setCaretPosition(document.getLength());
textPane.insertIcon(new ImageIcon(image));
document.insertString(document.getLength(), "\n", getFriendAttribute());
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 获取某种字体
* @param name 字体名称
* @param size 字体大小
* @param color 字体颜色
* @param bold 是否加粗
* @param underline 是否加下划线
* @return 返回获取的字体
*/
public static SimpleAttributeSet getFontAttribute(String name, int size, Color color,
boolean bold, boolean underline)
{
SimpleAttributeSet attribute = new SimpleAttributeSet();
StyleConstants.setFontFamily(attribute, name);
StyleConstants.setFontSize(attribute, size);
StyleConstants.setForeground(attribute, color);
StyleConstants.setBold(attribute, bold);
StyleConstants.setUnderline(attribute, underline);
return attribute;
}
public static SimpleAttributeSet getMyAttribute()
{
return getFontAttribute("楷体", 22, Color.red, false, true);
}
public static SimpleAttributeSet getFriendAttribute()
{
return getFontAttribute("黑体", 16, Color.blue, false, false);
}
public static SimpleAttributeSet getTimeAttribute()
{
return getFontAttribute("黑体", 14, Color.DARK_GRAY, false, false);
}
}
================================================
FILE: src/client/common/MyTreeIcon.java
================================================
package client.common;
import java.awt.Component;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.GrayFilter;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
import client.control.Main;
import com.MyTools;
public class MyTreeIcon extends DefaultTreeCellRenderer
{
//如果是:用户名;图片路径,那么就是好友节点
//如果是:用户名;图片路径1;图片路径2,那么表示分组节点,
//图片路径1表示未展开的分组,图片路径2表示展开了的分组
ArrayList<String> nodeImages=null;
public MyTreeIcon(ArrayList<String> nodeImages)
{
this.nodeImages=nodeImages;
}
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus)
{
super.getTreeCellRendererComponent(tree, value, sel,expanded,
leaf, row, hasFocus);
for(String str:nodeImages)
{
String[] temp=str.split(MyTools.SPLIT1);
if(value.toString().startsWith(temp[0])&&!temp[0].equals(""))//注意Value一定要toString()
{
try
{
//Image grayImage = GrayFilter.createDisabledImage(ImageIO.read(Main.class.getResource(temp[1])));
if(temp.length==2)//如果是:用户名;图片路径,那么就是好友节点
//this.setIcon(new ImageIcon(grayImage));
this.setIcon(MyTools.getIcon(temp[1]));
else if(temp.length==3)//如果是:用户名;图片路径1;图片路径2,那么表示分组节点,
{
if(!expanded)
this.setIcon(MyTools.getIcon(temp[1]));
else
this.setIcon(MyTools.getIcon(temp[2]));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
return this;
}
}
================================================
FILE: src/client/control/Chat.java
================================================
package client.control;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import com.MyTools;
import com.MyTools.Flag;
import com.socket.TCP;
import com.socket.UDP;
import client.common.MyLabel;
import client.common.MyTextPane;
import client.control.Main;
import client.frame.ChatFrame;
import client.frame.FaceFrame;
import client.frame.ScreenFram;
import client.frame.SendFileFrame;
import client.socket.CC_TCP;
import client.socket.CS_TCP;
import client.socket.S_TCP;
import client.socket.UDPChat;
/**
* @author LXA 聊天的窗体,继承自ChatFrame
*/
public class Chat extends ChatFrame
{
public String friendIP = null;// 好友的IP地址
public int friendTCPPort=0;//好友的TCP端口
public String friendName="";//好友的名字
public String myName="";//自己的名字
public CC_TCP cc_TCP=null;//发起聊天的TCP
public TCP tcp=null;//接收聊天的TCP
public UDPChat chatUDP=null;
int width = 680;// 窗体宽度
int height = 600;// 窗体高度
private StyledDocument receiveDocument = null;// 用来存放接收框的文本或图片
private StyledDocument sendDocument = null;// 用来存放发送框的文本或图片
public ServerSocket getFileServer=null;
public int myGetFilePort=10000;
public int friendGetFilePort=0;
public CS_TCP cs_TCP=null;//用来当对方不在线时给服务器发送离线消息
public String ImgPath = "";
String screenCutImgName = "";
public int faceIdx=-1;//表情的索引
/**
* 通过UDP构造聊天窗体
*/
/*public Chat(String friendIP,String friendName,String myName)
{
chatUDP=new UDPChat(friendIP,this);//实例化一个已经封装好的ChatUDP类
init();
}*/
/**
* 通过TCP主动发起聊天
* @param friendIP
* @param friendTCPPort
* @param friendName
* @param myName
*/
public Chat(String friendIP,int friendTCPPort,String friendName,String myName)
{
this.friendIP=friendIP;
this.friendTCPPort=friendTCPPort;
this.friendName=friendName;
this.myName=myName;
try
{
cc_TCP=new CC_TCP(this.friendIP, this.friendTCPPort,this);
cc_TCP.sendMessage(Flag.START_CHAT+MyTools.FLAGEND+myName);//发起聊天请求
}
catch (Exception e)
{
e.printStackTrace();
}
init();
initGetFileServer();//初始化接收文件的服务
}
/**
* 通过TCP被动接受聊天
* @param tcp
* @param friendName
* @param myName
*/
public Chat(TCP tcp,String friendName,String myName)
{
this.tcp=tcp;
this.friendName=friendName;
this.myName=myName;
init();
initGetFileServer();//初始化接收文件的服务
}
/**
* 发送离线消息时的构造方法
* @param cs_TCP
* @param friendName
*/
public Chat(CS_TCP cs_TCP,String friendName)
{
this.cs_TCP=cs_TCP;
this.friendName=friendName;
init();
setTitle("给"+friendName+"发送离线消息中……");
}
public void init()
{
this.setMinimumSize(new Dimension(width, height));// 设置窗体的最小大小
if(cc_TCP!=null)//如果是发起方则直接设置标题,接收方因为对方IP还未知,所以这里还不能设置
setTitle("与" + friendName+"("+friendIP+":"+friendTCPPort+")聊天中");// 设置窗体标题
initLabelEvent();// 初始化窗体上所有Label的鼠标移动事件
MyTools.setWindowsMiddleShow(this,width,height);//设置窗体居中显示
jButton发送.setMnemonic(KeyEvent.VK_ENTER);// 设置发送按钮的快捷键为Alt+Enter
receiveDocument = jTextPane接收框.getStyledDocument();
sendDocument = jTextPane发送框.getStyledDocument();
jTextPane接收框.insertIcon(MyTools.getIcon("../img/warning.png"));
String warning="交谈中请勿轻信汇款、中奖信息、陌生电话,勿使用外挂软件。\n";
try
{
SimpleAttributeSet warn=MyTextPane.getFontAttribute("黑体", 12, Color.blue, false, false);
receiveDocument.insertString(receiveDocument.getLength(), warning, warn);
// 设置窗体的顶部图标
this.setIconImage(ImageIO.read(Main.class.getResource("../img/QQ_64.png")));
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 初始化接收文件的服务
*/
public void initGetFileServer()
{
while (true)
{
try
{
getFileServer = new ServerSocket(myGetFilePort);
System.out.println("已开启文件接收监听!");
if(cc_TCP!=null)
cc_TCP.sendMessage(Flag.SENDFILE+MyTools.FLAGEND+myGetFilePort);
else
tcp.sendMessage(Flag.SENDFILE+MyTools.FLAGEND+myGetFilePort);
break;
}
catch (Exception e)
{
myGetFilePort++;
}
}
Runnable runnable=new Runnable()
{
@Override
public void run()
{
//tcp.sendMessage(Flag.GETFILE_OK+MyTools.FLAGEND+TCP.getLocalHostIP()+MyTools.SPLIT1+myPort);
RecieveThread recieveThread;
while (true)
{
try
{
Socket socket = getFileServer.accept();
System.out.println("与文件发送方连接成功!");
recieveThread = new RecieveThread(new SendFileFrame(), socket);
recieveThread.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
new Thread(runnable).start();
}
/**
* 初始化窗体上所有Label的鼠标移动事件
*/
public void initLabelEvent()
{
new MyLabel(jLabel字体).addEvent();
new MyLabel(jLabel表情).addEvent();
new MyLabel(jLabel音乐).addEvent();
new MyLabel(jLabel图片).addEvent();
new MyLabel(jLabel截图).addEvent();
new MyLabel(jLabel聊天记录).addEvent();
new MyLabel(jLabel视频).addEvent();
new MyLabel(jLabel语音).addEvent();
new MyLabel(jLabel发送文件).addEvent();
new MyLabel(jLabelQQ空间).addEvent();
new MyLabel(jLabel我的好友).addEvent();
new MyLabel(jLabel加好友).addEvent();
}
/*
* 给好友发送消息
*/
@Override
public void sendMessage()
{
//发送的是文本信息
if ("".equals(ImgPath) && "".equals(screenCutImgName))
{
if(faceIdx<0)
{
if(cc_TCP!=null)//如果是发起聊天的一方
cc_TCP.sendMessage(Flag.MESSAGE+MyTools.FLAGEND+jTextPane发送框.getText());
else if(tcp!=null)//如果是接收聊天的一方
tcp.sendMessage(Flag.MESSAGE+MyTools.FLAGEND+jTextPane发送框.getText());
else if(cs_TCP!=null)//发送未读消息
cs_TCP.sendMessage(Flag.UNDERLINE_MESSAGE+MyTools.FLAGEND+friendName+MyTools.SPLIT1+jTextPane发送框.getText());
setReceivePaneText(true,jTextPane发送框.getText());//将用户发送的消息显示在聊天框中
jTextPane发送框.setText("");// 清空发送框
}
else
{
if(cc_TCP!=null)//如果是发起聊天的一方
cc_TCP.sendMessage(Flag.FACE+MyTools.FLAGEND+faceIdx);
else if(tcp!=null)//如果是接收聊天的一方
tcp.sendMessage(Flag.FACE+MyTools.FLAGEND+faceIdx);
new MyTextPane(jTextPane接收框).addIcon(MyTools.getFaceByIdx(faceIdx), myName);
jTextPane发送框.setText("");// 清空发送框
faceIdx=-1;//图片表情发完后置为默认
}
}
//发送的是图片
else if(!"".equals(ImgPath))
{
try
{
//置空发送框
jTextPane发送框.setText("");
//接收框显示图片
jTextPane接收框.insertIcon(new ImageIcon(ImageIO
.read(new FileInputStream(ImgPath))));
//发送图片给对方
cc_TCP.sendImg(ImgPath);
//发送完图片后置空图片路径
ImgPath ="";
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(!"".equals(screenCutImgName))
{
try
{ //置空发送框
jTextPane发送框.setText("");
//接收框显示图片
jTextPane接收框.insertIcon(new ImageIcon(ImageIO
.read(new FileInputStream("./screenCut/snap.jpg"))));
//发送图片给对方
cc_TCP.sendImg("./screenCut/snap.jpg");
//发送完图片后置空图片路径
screenCutImgName ="";
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 设置发送框文本
*
* @param text
* 需要设置的文本
*/
public void setSendPaneText(String text)
{
try
{
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 设置接收框的文本
*
* @param text
* 需要设置的文本
*/
public void setReceivePaneText(boolean isFromMyself, String text)
{
if (isFromMyself)
{
String time= DateFormat.getTimeInstance().format(new Date());
new MyTextPane(jTextPane接收框).addText(myName+" "+time+ "\n",MyTextPane.getTimeAttribute());
new MyTextPane(jTextPane接收框).addText(text+ "\n",MyTextPane.getMyAttribute());
}
else
{
String time= DateFormat.getTimeInstance().format(new Date());
new MyTextPane(jTextPane接收框).addText(friendName+" "+time+ "\n",MyTextPane.getTimeAttribute());
new MyTextPane(jTextPane接收框).addText(text+ "\n",MyTextPane.getFriendAttribute());
}
}
/**
* 发送文件
*/
public void sendFile()
{
System.out.println("对方已开启文件接收监听!");
SendFileFrame sendFileFrame=new SendFileFrame();
sendFileFrame.lblProgress.setText("正在等待文件被接收....");
String filePath = sendFileFrame.showDialog(JFileChooser.FILES_ONLY);
sendFileFrame.setVisible(true);
SendTread sendThread;
//sendThread = new SendTread(sendFileFrame, filePath,message.split(MyTools.SPLIT1)[0],Integer.parseInt(message.split(MyTools.SPLIT1)[1]));
sendThread = new SendTread(sendFileFrame, filePath,friendIP,friendGetFilePort);
sendThread.start();
}
/*
* 发生在窗体关闭之前
*/
public void beforeClose()
{
}
public void selectFace()
{
new FaceFrame(this);
}
/*
* 发送图片
*/
public void sendImg()
{
JFileChooser chooser = new JFileChooser();
// 添加过滤器
chooser.addChoosableFileFilter(new FileFilter()
{
@Override
public String getDescription()
{
// TODO Auto-generated method stub
return ".jpg/.png/.bmp";
}
@Override
public boolean accept(File file)
{
// 获取文件名
String fileName = file.getName();
if (file.isDirectory())
return true;
// 过滤文件名
if (fileName.endsWith(".jpg") || fileName.endsWith(".png")
|| fileName.endsWith(".bmp"))
{
return true;
}
return false;
}
});
int result = chooser.showOpenDialog(null);
// 选择打开时
if (result == JFileChooser.APPROVE_OPTION)
{
String filePath = chooser.getSelectedFile().getAbsolutePath();
// 给图片添加;路径
ImgPath = filePath;
try
{
jTextPane发送框.insertIcon(new ImageIcon(ImageIO
.read(new FileInputStream(filePath))));
}
catch (FileNotFoundException e)
{
System.out.println("文件未找到");
e.printStackTrace();
}
catch (IOException e)
{
System.out.println("io异常");
e.printStackTrace();
}
}
// 选择关闭是
else
{
dispose();
}
}
/*
* @截图
*/
@Override
public void screenFram()
{
try
{
ScreenFram.main();
System.out.println("截图的名字是"+screenCutImgName);
jTextPane发送框.insertIcon(new ImageIcon(ImageIO
.read(new FileInputStream("./screenCut/snap.jpg"))));
screenCutImgName="snap";
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
================================================
FILE: src/client/control/Login.java
================================================
package client.control;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JOptionPane;
import com.MyTools;
import com.MyTools.Flag;
import client.common.MyLabel;
import client.frame.LoginFrame;
import client.frame.RegisterFrame;
import client.socket.CS_TCP;
import com.sun.awt.AWTUtilities;//这个导入很重要,不导入报错,导入但又警告,所以不要理警告
/**
* @author LXA
* 登录窗体,继承自LoginFrame
*/
public class Login extends LoginFrame
{
/**
*
*/
private static final long serialVersionUID = 5055331246882705423L;
int width=350;
int height=266;
private Point lastPoint = null;//存放按下鼠标时的坐标点
public CS_TCP cs_TCP=null;//声明一个客户端TCP
public Main main; //声明一个主窗体
public RegisterFrame registerFrame=null;
/**
* 程序的主入口
* @param args
*/
public static void main(String[] args)
{
MyTools.changeSkin();//更换皮肤
new Login();
}
/**
* 登录窗体的构造方法
*/
public Login()
{
init();
}
/**
* 初始化
*/
public void init()
{
MyTools.setWindowsMiddleShow(this,width,height);//设置窗体居中显示
new MyLabel(lbl登录, "../img/button/button_login", "png").addEvent();
new MyLabel(lbl最小化, "../img/button/login_minsize", "png").addEvent();
new MyLabel(lbl退出, "../img/button/login_exit", "png").addEvent();
new MyLabel(lbl多账号, "../img/button/login_duozhanghao", "png").addEvent();
new MyLabel(lbl设置, "../img/button/login_setting", "png").addEvent();
new MyLabel(lbl注册账号).addEvent();
initUserStatus();
AWTUtilities.setWindowOpaque(this, false);//设置窗体完全透明
addEvent();
this.setVisible(true);
main=new Main();
}
/**
* 初始化用户是否在线等状态
*/
public void initUserStatus()
{
comboBox状态.removeAllItems();
comboBox状态.addItem(MyTools.getIcon("../img/status/status_online_12.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_qme_12.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_leave_12.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_busy_12.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_invisible_12.png"));
}
/**
* 登录到服务器
*/
public void login()
{
String name=textField用户名.getText();
String password=new String(pwd密码.getPassword());
if(name.equals("")||password.equals(""))
JOptionPane.showMessageDialog(this, "用户名和密码不能为空!","错误",JOptionPane.ERROR_MESSAGE);
else
{
try
{
if(cs_TCP==null)
cs_TCP=new CS_TCP(MyTools.QQServerIP, MyTools.QQServerPort,this,main);
System.out.println("开始检测用户名和密码……");
cs_TCP.sendMessage(Flag.LOGIN+MyTools.FLAGEND+name+MyTools.SPLIT1+password+MyTools.SPLIT1+main.getServerPort()+MyTools.SPLIT1+comboBox状态.getSelectedIndex());
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "连接服务器失败!请检查网络连接或确保QQ服务器已启动!");
}
}
}
/**
* 处理窗体的鼠标按下事件
* @param e
*/
public void mousePress(MouseEvent e)
{
lastPoint = e.getLocationOnScreen();
}
/**
* 处理窗体的拖拽事件
* @param e
*/
public void mouseDrag(MouseEvent e)
{
Point point = e.getLocationOnScreen();
int offsetX = point.x - lastPoint.x;
int offsetY = point.y - lastPoint.y;
Rectangle bounds = this.getBounds();
bounds.x += offsetX;
bounds.y += offsetY;
this.setBounds(bounds);
lastPoint = point;
}
/**
* 给窗体添加事件
*/
public void addEvent()
{
lbl登录.addMouseListener(new MouseAdapter()
{
//登录按钮的单击事件
@Override
public void mouseClicked(MouseEvent e)
{
login();
}
});
this.addMouseListener(new MouseAdapter()
{
//窗体的鼠标按下事件
@Override
public void mousePressed(MouseEvent e)
{
mousePress(e);
}
});
this.addMouseMotionListener(new MouseAdapter()
{
@Override
public void mouseDragged(MouseEvent e)
{
mouseDrag(e);
};
});
lbl退出.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
System.exit(0);
}
});
lbl最小化.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
JOptionPane.showMessageDialog(null, "功能暂未实现!敬请期待!", "温馨提示", JOptionPane.INFORMATION_MESSAGE);
}
});
lbl多账号.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
JOptionPane.showMessageDialog(null, "功能暂未实现!敬请期待!", "温馨提示", JOptionPane.INFORMATION_MESSAGE);
}
});
lbl设置.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
JOptionPane.showMessageDialog(null, "功能暂未实现!敬请期待!", "温馨提示", JOptionPane.INFORMATION_MESSAGE);
}
});
lbl注册账号.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
new Register();
}
});
}
}
================================================
FILE: src/client/control/Main.java
================================================
package client.control;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import com.MyTools;
import com.MyTools.Flag;
import com.socket.TCPServer;
import client.common.*;
import client.control.MyTree;
import client.frame.MainFrame;
import client.socket.CC_TCP;
import client.socket.CS_TCP;
import client.socket.S_TCP;
public class Main extends MainFrame
{
public CS_TCP cs_TCP=null;
public S_TCP s_TCP=null;
private int serverPort=5000;//端口从5000开始分配
final int width=350;//窗体宽度
final int height=630;//窗体高度
public QunChat qunChat;//群聊天室
public Main()
{
init();
}
public Main(CS_TCP cs_TCP)
{
this.cs_TCP=cs_TCP;
init();
}
/**
* 初始化主窗体
*/
public void init()
{
new MyLabel(lbl设置,"../img/button/QQ_settings","png").addEvent();//给最底下的设置按钮添加事件
MyTools.setWindowsMiddleShow(this,width,height);//设置窗体居中显示
initUserStatus();//初始化用户是否在线等状态
s_TCP=new S_TCP(serverPort,this);
}
/**
* 当登录成功后,将登录窗体的CS_TCP传给主窗体
* @param cs_TCP
*/
public void setCS_TCP(CS_TCP cs_TCP)
{
this.cs_TCP=cs_TCP;
}
public int getServerPort()
{
return s_TCP.getServerPort();
}
/**
* 初始化用户是否在线等状态
*/
public void initUserStatus()
{
comboBox状态.removeAllItems();
comboBox状态.addItem(MyTools.getIcon("../img/status/status_online.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_qme.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_leave.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_busy.png"));
comboBox状态.addItem(MyTools.getIcon("../img/status/status_invisible.png"));
}
/**
* 初始化好友列表
*/
public void initjTree(String[] groupNames,ArrayList<String[]> friendNames)
{
new MyTree(tree, groupNames, friendNames);
}
/*
* 开始给对方好友聊天
*/
@Override
public void startChat(ActionEvent e)
{
if(tree.getSelectionPath().getPathCount()==3)
{
String str=tree.getSelectionPath().getLastPathComponent().toString();
String friendName=str.substring(0,str.indexOf("("));
String friendIP=str.substring(str.indexOf("(")+1,str.indexOf(":"));
int friendPort=Integer.parseInt(str.substring(str.indexOf(":")+1,str.indexOf(")")));
if(!friendIP.equals("下线或隐身"))
{
Chat chat=new Chat(friendIP,friendPort,friendName,this.lbl用户名.getText());
chat.setVisible(true);
}
else
{
Chat chat=new Chat(cs_TCP, friendName);
chat.setVisible(true);
}
}
else
{
JOptionPane.showMessageDialog(null, "对不起,您未选中任何好友!");
}
}
/*
* 请求获取好友资料
*/
@Override
public void getFriendInfo(ActionEvent e)
{
String str=tree.getSelectionPath().getLastPathComponent().toString();
String userName=str.substring(0,str.indexOf("("));
cs_TCP.sendMessage(Flag.GET_FRIEND_INFO+MyTools.FLAGEND+userName);
}
/**
* 发送文件
* @param e
*/
@Override
public void sendFile(ActionEvent e)
{
}
/**
* 删除好友
* @param e
*/
public void deleteFriend(ActionEvent e)
{
DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
node.removeFromParent();
JOptionPane.showMessageDialog(null, "删除好友成功!请关闭并打开当前分组以刷新好友列表!");
}
/**
* 进入聊天室
*/
@Override
public void gotoChatRoom()
{
qunChat=new QunChat(this);
}
/**
* 新建聊天室
*/
@Override
public void buildNewChatRoom()
{
JOptionPane.showMessageDialog(null, "新建聊天室属于会员专属功能,您还不是会员,是否想要加入会员,更多功能等你玩转,仅需10元每月哦!","提示",JOptionPane.YES_NO_CANCEL_OPTION);
}
}
================================================
FILE: src/client/control/MyTree.java
================================================
package client.control;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import com.MyTools;
import client.common.MyTreeIcon;
public class MyTree
{
private JTree tree;//存放好友列表的树
private DefaultTreeModel treeModel;//好友树的数据
private String[] groupNames=null;//好友分组信息
ArrayList<String> nodeImages;//存放节点的头像,示例:张三;02_100.jpg
private ArrayList<String[]> friendInfos=new ArrayList<String[]>();//每个分组的好友信息
public MyTree(JTree tree,String[] groupNames,ArrayList<String[]> friendInfos)
{
this.tree=tree;
this.groupNames=groupNames;
this.friendInfos=friendInfos;
init();//初始化
addEvent();//添加事件
}
public MyTree(JTree tree)
{
this.tree=tree;
treeModel=(DefaultTreeModel) tree.getModel();
}
/**
* 初始化
*/
public void init()
{
tree.setRootVisible(false);//设置根节点不可见
tree.setAutoscrolls(true);//设置自动滚动
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);//设置单选模式
nodeImages=new ArrayList<String>();
nodeImages.add("所有在线用户"+MyTools.SPLIT1+"../img/face/f023.png"+MyTools.SPLIT1+"../img/face/f019.png");
nodeImages.add("所有不在线用户"+MyTools.SPLIT1+"../img/face/f035.png"+MyTools.SPLIT1+"../img/face/f033.png");
nodeImages.add("我的好友"+MyTools.SPLIT1+"../img/face/f051.png"+MyTools.SPLIT1+"../img/face/f049.png");
DefaultMutableTreeNode root=new DefaultMutableTreeNode("root");
treeModel=new DefaultTreeModel(root);//新建一个用于存放好友树的Model
for(int i=0;i<groupNames.length;i++)
{
DefaultMutableTreeNode node=new DefaultMutableTreeNode(groupNames[i]);
for(int j=0;j<friendInfos.get(i).length;j++)
{
String[] temp=friendInfos.get(i)[j].split(MyTools.SPLIT3);
//System.out.println(friendInfos.get(i)[j]);
String friendName=temp[0];//好友用户名
String ip=temp[1];//好友IP地址
String port=temp[2];//好友的端口号
String headImage=temp[3];//好友头像
String state=temp[4];//状态
nodeImages.add(friendName+MyTools.SPLIT1+"../img/headImage/small/"+headImage+"_32.jpg");
node.add(new DefaultMutableTreeNode(friendName+"("+ip+":"+port+")"));
}
root.add(node);
}
tree.setCellRenderer(new MyTreeIcon(nodeImages));
tree.setModel(treeModel);
}
/**
* 以最简单的方式设置树的节点的三种状态的图标,没什么用暂且当做示例代码留在这里
*/
public void setNodeImage()
{
/*DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
renderer.setLeafIcon(GetIcon.getIcon("../img/f051.png"));//设置叶子节点的图标
renderer.setClosedIcon(GetIcon.getIcon("../img/f021.png"));//设置未展开的节点的图标
renderer.setOpenIcon(GetIcon.getIcon("../img/f019.png"));//设置已展开的节点图标
tree.setCellRenderer(renderer);*/
}
/**
* 添加事件
*/
public void addEvent()
{
tree.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
int selRow = tree.getRowForLocation(e.getX(), e.getY());
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if(selRow != -1)
{
/*if(e.getClickCount() == 1) {
JOptionPane.showMessageDialog(null, "单击:"+selRow+","+selPath);
}
else if(e.getClickCount() == 2) {
// myDoubleClick(selRow, selPath);
JOptionPane.showMessageDialog(null, "双击:"+selRow+","+selPath);
}*/
if(selPath.toString().split(",").length>2)//selPath的结果示例:“root,我的好友”
{
}
}
// System.out.println(tree.getSelectionPath());
}
});
}
/**
* 添加新的好友分组到树
* @param groupName 分组名字
*/
public void addGroupToTree(String groupName)
{
DefaultMutableTreeNode childNode=new DefaultMutableTreeNode(groupName);
DefaultMutableTreeNode parent=(DefaultMutableTreeNode) treeModel.getRoot();
treeModel.insertNodeInto(childNode, parent, parent.getChildCount());
}
/**
* 添加新的好友到指定的分组
* @param groupIndex 分组
* @param friendName 要添加的好友的名字
*/
public void addFriendToTree(String groupName,String friendName)
{
int groupIndex=treeModel.getIndexOfChild((DefaultMutableTreeNode)treeModel.getRoot(), new DefaultMutableTreeNode(groupName));
DefaultMutableTreeNode childNode=new DefaultMutableTreeNode(friendName);
if(groupIndex!=-1)
{
DefaultMutableTreeNode parent=(DefaultMutableTreeNode) treeModel.getChild(treeModel.getRoot(), groupIndex);
treeModel.insertNodeInto(childNode, parent, parent.getChildCount());
}
else
System.out.println("好友组“"+groupName+"”不存在!");
}
/**
* 删除树里面的某个好友
*/
public void deleteFriend(String groupName,String friendName)
{
DefaultMutableTreeNode root=(DefaultMutableTreeNode) treeModel.getRoot();
for(int i=0;i<root.getChildCount();i++)
{
if(root.getChildAt(i).toString().startsWith(groupName))
{
for(int j=0;j<root.getChildAt(i).getChildCount();j++)
{
if(root.getChildAt(i).getChildAt(j).toString().startsWith(friendName))
{
System.out.println(root.getChildAt(i).getChildAt(j));
DefaultMutableTreeNode node=(DefaultMutableTreeNode)root.getChildAt(i).getChildAt(j);
node.removeFromParent();
System.out.println("删除成功!");
}
break;
}
}
break;
}
}
/**
* 打开某个好友分组
* @param groupName
*/
public void openGroup(String groupName)
{
DefaultMutableTreeNode childNode=new DefaultMutableTreeNode(groupName);
tree.scrollPathToVisible(new TreePath(childNode.getPath()));//自动打开到当前节点
}
}
================================================
FILE: src/client/control/QunChat.java
================================================
package client.control;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.Date;
import javax.swing.JTree;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyledDocument;
import javax.swing.tree.TreeModel;
import com.MyTools;
import com.MyTools.Flag;
import client.common.MyTextPane;
import client.common.MyTreeIcon;
import client.frame.QunChatFrame;
import client.socket.CS_TCP;
public class QunChat extends QunChatFrame
{
CS_TCP cs_TCP=null;
Main main=null;
public QunChat(Main main)
{
this.main=main;
this.tree.setModel(main.tree.getModel());
this.tree.setCellRenderer(main.tree.getCellRenderer());
this.cs_TCP=main.cs_TCP;
MyTools.setWindowsMiddleShow(this);
this.setTitle("MyQQ官方聊天室(当前用户:"+main.lbl用户名.getText()+")");
addEvent();
this.setVisible(true);
}
public void addEvent()
{
btn发送.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String nowTime= DateFormat.getTimeInstance().format(new Date());
cs_TCP.sendMessage(Flag.QUN_CHAT+MyTools.FLAGEND+main.lbl用户名.getText()+MyTools.SPLIT1+nowTime+MyTools.SPLIT1+textPane发送.getText());
textPane发送.setText("");
}
});
btn关闭.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
dispose();//关闭聊天室
}
});
}
public void receiveMessage(String message)
{
String[] temp=message.split(MyTools.SPLIT1);
if(temp[0].equals(main.lbl用户名.getText()))
{
new MyTextPane(textPane接收框).addText(temp[0]+" "+temp[1]+"\n", MyTextPane.getTimeAttribute());
new MyTextPane(textPane接收框).addText(temp[2]+"\n", MyTextPane.getMyAttribute());
}
else
{
new MyTextPane(textPane接收框).addText(temp[0]+" "+temp[1]+"\n", MyTextPane.getTimeAttribute());
new MyTextPane(textPane接收框).addText(temp[2]+"\n", MyTextPane.getFriendAttribute());
}
}
public void showPublicMessage(String message)
{
textArea群公告.setText(message);
}
}
================================================
FILE: src/client/control/RecieveThread.java
================================================
package client.control;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import client.frame.SendFileFrame;
public class RecieveThread extends Thread
{
private SendFileFrame fram;
private Socket socket;
private DataInputStream in;
private DataOutputStream fileOut;
private ServerSocket ss;
private String serverPort;
public RecieveThread(SendFileFrame fram, Socket socket)
{
this.fram = fram;
this.socket = socket;
}
@Override
public void run()
{
super.run();
recieveFile();
}
public void recieveFile()
{
try
{
// ss = new ServerSocket(Integer.parseInt(serverPort));
// socket = ss.accept();
// TODO 测试连接是否成功
// JOptionPane.showMessageDialog(null, "接收端已成功连接!");
// socket = new Socket(ConnInfor.SERVER_IP, ConnInfor.CONN_PORT);
in = new DataInputStream(socket.getInputStream());
String filePath = null;
// 读取发过来的文件名和文件长度
String fileName = in.readUTF();
long fileLen = in.readLong();
// 弹出接收对话
int result = JOptionPane.showConfirmDialog(null, "是否接收文件?" + fileName,
"提示", JOptionPane.YES_NO_CANCEL_OPTION);
// 选择对话框中的取消按钮的相应操作
if (result == JOptionPane.CANCEL_OPTION)
{
}
// 选择对话框中的否按钮的相应操
else if (result == JOptionPane.NO_OPTION)
{
closeRecieve();
}
// 选择对话框中的是按钮的相应操
else if (result == JOptionPane.OK_OPTION)
{
filePath = fram.showDialog(JFileChooser.DIRECTORIES_ONLY);
fram.setVisible(true);
fileOut = new DataOutputStream(new FileOutputStream(filePath
+ "/"+fileName));
byte[] buff = new byte[1024];
int len = 0;
long passLen = 0;
long startTime = System.currentTimeMillis();
long endTime = 0;
long passTime = 0;
while (true)
{
if (in != null)
{
len = in.read(buff);
passLen += len;
}
endTime = System.currentTimeMillis();
passTime = endTime - startTime;
if (len == -1)
{
fram.updateProgressBar(fram.progressBar, fileLen,
fileLen, fram.lblProgress, passTime);
break;
}
fram.updateProgressBar(fram.progressBar, passLen,
fileLen, fram.lblProgress, passTime);
fileOut.write(buff, 0, len);
}
}
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
closeRecieve();
}
}
/**
* 关闭接收连接
*
*/
public void closeRecieve()
{
try
{
if (fileOut != null)
fileOut.close();
if (in != null)
{
in.close();
}
if (socket != null)
{
socket.close();
}
if (ss != null)
{
ss.close();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
================================================
FILE: src/client/control/Register.java
================================================
package client.control;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import com.MyTools;
import com.MyTools.Flag;
import client.frame.LoginFrame;
import client.frame.RegisterFrame;
import client.socket.CS_TCP;
import server.common.JDBC;
import server.dao.UserDao;
import server.entity.Users;
/**
* @author Administrator
*注册最后得到的是一个user对象
*user对象内容为用户名,密码,头像,生日,签名,E-mail.
*/
public class Register extends RegisterFrame
{
//UserDao ud = new UserDao();
public CS_TCP cs_TCP;//客户端与服务器的TCP连接
public Register()
{
MyTools.setWindowsMiddleShow(this);
initHeadImage();
addEvent();
setVisible(true);
}
/**
* 初始化头像
*/
public void initHeadImage()
{
for(int i=0;i<=15;i++)
{
comboBoxHeadImage.addItem(MyTools.getIcon("../img/headImage/big/"+i+"_100.jpg"));
}
}
public void addEvent()
{
btnRegister.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if(txtName.getText().equals(""))
JOptionPane.showMessageDialog(null, "用户名不能为空!","错误",JOptionPane.ERROR_MESSAGE);
else if(new String(pwd.getPassword()).equals(""))
JOptionPane.showMessageDialog(null, "密码不能为空!","错误",JOptionPane.ERROR_MESSAGE);
else if(!new String(pwd.getPassword()).equals(new String(pwdRe.getPassword())))
JOptionPane.showMessageDialog(null, "两次输入的密码不一致,请重新输入!","错误",JOptionPane.ERROR_MESSAGE);
else
{
try
{
if(cs_TCP==null)
cs_TCP=new CS_TCP(MyTools.QQServerIP, MyTools.QQServerPort);
String sex="男";
if(comGender.getSelectedIndex()==1)
sex="女";
cs_TCP.sendMessage(Flag.REGISTER+MyTools.FLAGEND//注册标志
+txtName.getText()+MyTools.SPLIT1//用户名
+new String(pwd.getPassword())+MyTools.SPLIT1//密码
+sex+MyTools.SPLIT1//性别
+txtEmail.getText()+MyTools.SPLIT1//电子邮件
+txtbirthday.getText()+MyTools.SPLIT1//生日
+txtSignat.getText()+MyTools.SPLIT1//个性签名
+comboBoxHeadImage.getSelectedIndex());//头像索引
}
catch (Exception ee)
{
JOptionPane.showMessageDialog(null, "连接服务器失败!请检查您的网络连接或确保服务器已启动!","错误",JOptionPane.ERROR_MESSAGE);
}
}
}
});
}
/**
* 在窗体关闭之前需要做的事
*/
@Override
public void beforeClose()
{
if(cs_TCP!=null)
cs_TCP.closeSocket();
}
/**
* 取消按钮事件
*/
@Override
public void cancle()
{
if(cs_TCP!=null)
cs_TCP.closeSocket();
this.dispose();
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
/*String btnStr = e.getActionCommand();
if ("注册".equals(btnStr))
{
if ((new String(registerFrame.pwd.getPassword()))
.equals(new String(registerFrame.pwdRe.getPassword()))) {
Users user = new Users();
String userCheck = registerFrame.txtName.getText();
if (ud.queryByName(userCheck) != null) {
JOptionPane.showMessageDialog(null, "用户名已存在");
} else {
ud = new UserDao();
user.setName(registerFrame.txtName.getText());
user.setPwd(new String(registerFrame.pwd.getPassword()));
user.setGender(String.valueOf(registerFrame.comGender
.getSelectedItem()));
user.setEmail(registerFrame.txtEmail.getText());
user.setState("离线");
try {
user.setBirthday(java.sql.Date
.valueOf(registerFrame.txtbirthday.getText()));
user.setSignature(registerFrame.txtSignat.getText());
user.setHeadImg(headImg);
System.out.println(user.getName() + user.getEmail());
ud.add(user);//添加到了数据库
} catch (Exception e2) {
// TODO: handle exception
JOptionPane.showMessageDialog(null, "生日格式为1900-11-11,不能为空");
}
}
}
}*/
}
}
================================================
FILE: src/client/control/SendTread.java
================================================
package client.control;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JOptionPane;
import client.frame.SendFileFrame;
public class SendTread extends Thread
{
private SendFileFrame fram;
private String FilePath;
private Socket socket;
private DataInputStream fileIn;
private DataOutputStream out;
private String connIP;
private int clientPort;
public SendTread(SendFileFrame fram, String Filepath,String connIP,int clientPort)
{
this.fram = fram;
this.FilePath = Filepath;
this.connIP = connIP;
this.clientPort = clientPort;
}
@Override
public void run()
{
super.run();
startSend( FilePath);
}
public void startSend(String filepath)
{
try
{
// ss = new ServerSocket(ConnInfor.CONN_PORT);
// socket = ss.accept();
socket = new Socket(connIP, clientPort);
// JOptionPane.showMessageDialog(null, "发送端已成功建立连接!");
File file = new File(filepath);
out = new DataOutputStream(socket.getOutputStream());
String fileName = file.getName();
long FileLen = file.length();
out.writeUTF(fileName);
out.flush();
out.writeLong(FileLen);
out.flush();
fileIn = new DataInputStream(new FileInputStream(file));
byte[] buff = new byte[1024];
int len = 0;
long passLen = 0;
long startTime = System.currentTimeMillis();
long endTime = 0;
double passTime = 0;
while (true)
{
if (fileIn != null)
{
len = fileIn.read(buff);
passLen += len;
}
endTime = System.currentTimeMillis();
passTime = endTime -startTime;
if (len == -1)
{
fram.updateProgressBar(fram.progressBar, FileLen,
FileLen, fram.lblProgress,passTime);
//fram.afterSendFile() ;
break;
}
fram.updateProgressBar(fram.progressBar, passLen, FileLen,
fram.lblProgress,passTime);
out.write(buff, 0, len);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
closeSend();
}
}
public void closeSend()
{
try
{
if (out != null)
out.close();
if (fileIn != null)
fileIn.close();
if (socket != null)
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
================================================
FILE: src/client/frame/ChatFrame.form
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.5" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
<Properties>
<Property name="defaultCloseOperation" type="int" value="2"/>
<Property name="title" type="java.lang.String" value="聊天"/>
<Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor">
<Color blue="ff" green="ff" red="cc" type="rgb"/>
</Property>
</Properties>
<SyntheticProperties>
<SyntheticProperty name="formSizePolicy" type="int" value="1"/>
</SyntheticProperties>
<Events>
<EventHandler event="windowClosing" listener="java.awt.event.WindowListener" parameters="java.awt.event.WindowEvent" handler="formWindowClosing"/>
</Events>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<Component id="jPanel左侧面板" max="32767" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jPanel右侧面板" min="-2" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jPanel右侧面板" alignment="0" max="32767" attributes="0"/>
<Component id="jPanel左侧面板" alignment="1" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel右侧面板">
<Properties>
<Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor">
<Color blue="ff" green="ff" red="cc" type="rgb"/>
</Property>
</Properties>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jLabelQQ秀_对方" min="-2" max="-2" attributes="0"/>
<Component id="jLabelQQ秀_自己" alignment="0" min="-2" max="-2" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<Component id="jLabelQQ秀_对方" min="-2" max="-2" attributes="0"/>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Component id="jLabelQQ秀_自己" min="-2" pref="251" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="jLabelQQ秀_对方">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/qqshow/qqshow_girl_02_180.jpg"/>
</Property>
</Properties>
<AuxValues>
<AuxValue name="generateMnemonicsCode" type="java.lang.Boolean" value="true"/>
</AuxValues>
</Component>
<Component class="javax.swing.JLabel" name="jLabelQQ秀_自己">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/qqshow/qqshow_boy_01.jpg"/>
</Property>
</Properties>
</Component>
</SubComponents>
</Container>
<Container class="javax.swing.JPanel" name="jPanel左侧面板">
<Properties>
<Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor">
<Color blue="ff" green="ff" red="cc" type="rgb"/>
</Property>
</Properties>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jPanel顶部面板" alignment="0" max="32767" attributes="0"/>
<Component id="jPanel发送面板" alignment="0" max="32767" attributes="0"/>
<Component id="jPanel聊天面板" alignment="0" pref="486" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<Component id="jPanel顶部面板" min="-2" pref="89" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jPanel聊天面板" pref="260" max="32767" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jPanel发送面板" min="-2" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel顶部面板">
<Properties>
<Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor">
<Color blue="ff" green="cc" red="33" type="rgb"/>
</Property>
</Properties>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Component id="jLabel头像" min="-2" max="-2" attributes="0"/>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="jLabel视频" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jLabel语音" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jLabel发送文件" min="-2" max="-2" attributes="0"/>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="jLabelQQ空间" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="13" max="-2" attributes="0"/>
<Component id="jLabel我的好友" min="-2" max="-2" attributes="0"/>
<EmptySpace pref="23" max="32767" attributes="0"/>
<Component id="jLabel加好友" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="1" attributes="0">
<Component id="jLabel头像" alignment="1" min="-2" max="-2" attributes="0"/>
<Group type="103" alignment="1" groupAlignment="0" attributes="0">
<Component id="jLabel视频" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel语音" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel发送文件" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabelQQ空间" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel我的好友" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel加好友" alignment="0" min="-2" max="-2" attributes="0"/>
</Group>
</Group>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="jLabel头像">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/QQ_64.png"/>
</Property>
</Properties>
</Component>
<Component class="javax.swing.JLabel" name="jLabelQQ空间">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_qzone_54.png"/>
</Property>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
<Component class="javax.swing.JLabel" name="jLabel我的好友">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_myfeeds_54.png"/>
</Property>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
<Component class="javax.swing.JLabel" name="jLabel视频">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_video_54.png"/>
</Property>
<Property name="toolTipText" type="java.lang.String" value="开始视频"/>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
<Component class="javax.swing.JLabel" name="jLabel语音">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_voice_54.png"/>
</Property>
<Property name="toolTipText" type="java.lang.String" value="开始语音"/>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
<Component class="javax.swing.JLabel" name="jLabel发送文件">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_sendfile_54.png"/>
</Property>
<Property name="toolTipText" type="java.lang.String" value="发送文件"/>
</Properties>
<Events>
<EventHandler event="mouseClicked" listener="java.awt.event.MouseListener" parameters="java.awt.event.MouseEvent" handler="jLabel发送文件MouseClicked"/>
</Events>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
<Component class="javax.swing.JLabel" name="jLabel加好友">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_add_54.png"/>
</Property>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
</SubComponents>
</Container>
<Container class="javax.swing.JPanel" name="jPanel聊天面板">
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
<SubComponents>
<Container class="javax.swing.JScrollPane" name="jScrollPane1">
<AuxValues>
<AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
</AuxValues>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="Center"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
<SubComponents>
<Component class="javax.swing.JTextPane" name="jTextPane接收框">
<Properties>
<Property name="editable" type="boolean" value="false"/>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Container>
<Container class="javax.swing.JPanel" name="jPanel发送面板">
<Properties>
<Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor">
<Color blue="ff" green="ff" red="cc" type="rgb"/>
</Property>
</Properties>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jPanel工具面板" alignment="0" max="32767" attributes="0"/>
<Group type="102" alignment="1" attributes="0">
<EmptySpace pref="321" max="32767" attributes="0"/>
<Component id="jButton关闭" min="-2" pref="76" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jButton发送" min="-2" pref="77" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="5" max="-2" attributes="0"/>
</Group>
<Component id="jScrollPane3" alignment="0" pref="486" max="32767" attributes="0"/>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<Component id="jPanel工具面板" min="-2" pref="36" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jScrollPane3" min="-2" pref="96" max="-2" attributes="1"/>
<EmptySpace min="-2" pref="10" max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jButton发送" pref="35" max="32767" attributes="1"/>
<Component id="jButton关闭" alignment="0" pref="35" max="32767" attributes="1"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JButton" name="jButton发送">
<Properties>
<Property name="text" type="java.lang.String" value="发送"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="jButton发送ActionPerformed"/>
</Events>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
<Component class="javax.swing.JButton" name="jButton关闭">
<Properties>
<Property name="text" type="java.lang.String" value="关闭"/>
</Properties>
</Component>
<Container class="javax.swing.JPanel" name="jPanel工具面板">
<Properties>
<Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor">
<Color blue="ff" green="ff" red="cc" type="rgb"/>
</Property>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableLocal" type="java.lang.Boolean" value="true"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Component id="jLabel字体" min="-2" pref="36" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jLabel表情" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jLabel音乐" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jLabel图片" min="-2" max="-2" attributes="0"/>
<EmptySpace type="unrelated" max="-2" attributes="0"/>
<Component id="jLabel截图" min="-2" max="-2" attributes="0"/>
<EmptySpace pref="193" max="32767" attributes="0"/>
<Component id="jLabel聊天记录" min="-2" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jLabel字体" min="-2" max="-2" attributes="1"/>
<Component id="jLabel表情" alignment="0" min="-2" max="-2" attributes="1"/>
<Component id="jLabel音乐" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel图片" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel截图" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel聊天记录" alignment="0" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="jLabel字体">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_font_32.png"/>
</Property>
<Property name="toolTipText" type="java.lang.String" value="字体"/>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.EtchedBorderInfo">
<EtchetBorder>
<Color PropertyName="highlight" blue="ff" green="ff" red="cc" type="rgb"/>
<Color PropertyName="shadow" blue="ff" green="ff" red="cc" type="rgb"/>
</EtchetBorder>
</Border>
</Property>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
<Component class="javax.swing.JLabel" name="jLabel表情">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_face_32.png"/>
</Property>
<Property name="toolTipText" type="java.lang.String" value="表情"/>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
<Component class="javax.swing.JLabel" name="jLabel图片">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_picture_32.png"/>
</Property>
<Property name="toolTipText" type="java.lang.String" value="发送图片"/>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
<Component class="javax.swing.JLabel" name="jLabel音乐">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_music_32.png"/>
</Property>
<Property name="toolTipText" type="java.lang.String" value="发送音乐"/>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
<Component class="javax.swing.JLabel" name="jLabel截图">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_snap_32.png"/>
</Property>
<Property name="toolTipText" type="java.lang.String" value="截图"/>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
<Component class="javax.swing.JLabel" name="jLabel聊天记录">
<Properties>
<Property name="icon" type="javax.swing.Icon" editor="org.netbeans.modules.form.editors2.IconEditor">
<Image iconType="3" name="/client/img/chat/fun_message_history_32.png"/>
</Property>
<Property name="text" type="java.lang.String" value="聊天记录"/>
<Property name="toolTipText" type="java.lang.String" value="打开我的聊天记录"/>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
</SubComponents>
</Container>
<Container class="javax.swing.JScrollPane" name="jScrollPane3">
<AuxValues>
<AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
<SubComponents>
<Component class="javax.swing.JTextPane" name="jTextPane发送框">
<AuxValues>
<AuxValue name="JavaCodeGenerator_VariableModifier" type="java.lang.Integer" value="1"/>
</AuxValues>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Container>
</SubComponents>
</Container>
</SubComponents>
</Form>
================================================
FILE: src/client/frame/ChatFrame.java
================================================
/*
* ChatFrame.java
*
* Created on __DATE__, __TIME__
*/
package client.frame;
import java.awt.Color;
import javax.swing.UIManager;
import client.common.MyLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
*
* @author __USER__
*/
public class ChatFrame extends javax.swing.JFrame
{
/** Creates new form ChatFrame */
public ChatFrame()
{
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
//GEN-BEGIN:initComponents
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents()
{
jPanel右侧面板 = new javax.swing.JPanel();
jLabelQQ秀_对方 = new javax.swing.JLabel();
jLabelQQ秀_自己 = new javax.swing.JLabel();
jPanel左侧面板 = new javax.swing.JPanel();
jPanel顶部面板 = new javax.swing.JPanel();
jLabel头像 = new javax.swing.JLabel();
jLabelQQ空间 = new javax.swing.JLabel();
jLabel我的好友 = new javax.swing.JLabel();
jLabel视频 = new javax.swing.JLabel();
jLabel语音 = new javax.swing.JLabel();
jLabel发送文件 = new javax.swing.JLabel();
jLabel加好友 = new javax.swing.JLabel();
jPanel聊天面板 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane接收框 = new javax.swing.JTextPane();
jPanel发送面板 = new javax.swing.JPanel();
jButton发送 = new javax.swing.JButton();
jButton关闭 = new javax.swing.JButton();
javax.swing.JPanel jPanel工具面板 = new javax.swing.JPanel();
jLabel字体 = new javax.swing.JLabel();
jLabel表情 = new javax.swing.JLabel();
jLabel表情.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e)
{
selectFace();
}
});
jLabel图片 = new javax.swing.JLabel();
jLabel图片.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e)
{
sendImg();
}
});
jLabel音乐 = new javax.swing.JLabel();
jLabel截图 = new javax.swing.JLabel();
jLabel截图.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e)
{
screenFram();
}
});
jLabel聊天记录 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
jTextPane发送框 = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("\u804a\u5929");
setBackground(new java.awt.Color(204, 255, 255));
addWindowListener(new java.awt.event.WindowAdapter()
{
public void windowClosing(java.awt.event.WindowEvent evt)
{
formWindowClosing(evt);
}
});
jPanel右侧面板.setBackground(new java.awt.Color(204, 255, 255));
jLabelQQ秀_对方.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/qqshow/qqshow_girl_02_180.jpg"))); // NOI18N
jLabelQQ秀_自己.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/qqshow/qqshow_boy_01.jpg"))); // NOI18N
javax.swing.GroupLayout jPanel右侧面板Layout = new javax.swing.GroupLayout(
jPanel右侧面板);
jPanel右侧面板.setLayout(jPanel右侧面板Layout);
jPanel右侧面板Layout.setHorizontalGroup(jPanel右侧面板Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelQQ秀_对方).addComponent(jLabelQQ秀_自己));
jPanel右侧面板Layout.setVerticalGroup(jPanel右侧面板Layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addGroup(
jPanel右侧面板Layout
.createSequentialGroup()
.addComponent(jLabelQQ秀_对方)
.addGap(18, 18, 18)
.addComponent(jLabelQQ秀_自己,
javax.swing.GroupLayout.PREFERRED_SIZE, 251,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)));
jPanel左侧面板.setBackground(new java.awt.Color(204, 255, 255));
jPanel顶部面板.setBackground(new java.awt.Color(51, 204, 255));
jLabel头像.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/QQ_64.png"))); // NOI18N
jLabelQQ空间.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_qzone_54.png"))); // NOI18N
jLabel我的好友.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_myfeeds_54.png"))); // NOI18N
jLabel视频.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_video_54.png"))); // NOI18N
jLabel视频.setToolTipText("\u5f00\u59cb\u89c6\u9891");
jLabel语音.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_voice_54.png"))); // NOI18N
jLabel语音.setToolTipText("\u5f00\u59cb\u8bed\u97f3");
jLabel发送文件.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_sendfile_54.png"))); // NOI18N
jLabel发送文件.setToolTipText("\u53d1\u9001\u6587\u4ef6");
jLabel发送文件.addMouseListener(new java.awt.event.MouseAdapter()
{
public void mouseClicked(java.awt.event.MouseEvent evt)
{
jLabel发送文件MouseClicked(evt);
}
});
jLabel加好友.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_add_54.png"))); // NOI18N
javax.swing.GroupLayout jPanel顶部面板Layout = new javax.swing.GroupLayout(
jPanel顶部面板);
jPanel顶部面板.setLayout(jPanel顶部面板Layout);
jPanel顶部面板Layout
.setHorizontalGroup(jPanel顶部面板Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
jPanel顶部面板Layout
.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel头像)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel视频)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel语音)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel发送文件)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelQQ空间)
.addGap(13, 13, 13)
.addComponent(jLabel我的好友)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED,
23, Short.MAX_VALUE)
.addComponent(jLabel加好友)
.addContainerGap()));
jPanel顶部面板Layout
.setVerticalGroup(jPanel顶部面板Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
jPanel顶部面板Layout
.createSequentialGroup()
.addContainerGap()
.addGroup(
jPanel顶部面板Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel头像)
.addGroup(
jPanel顶部面板Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(
jLabel视频)
.addComponent(
jLabel语音)
.addComponent(
jLabel发送文件)
.addComponent(
jLabelQQ空间)
.addComponent(
jLabel我的好友)
.addComponent(
jLabel加好友)))
.addContainerGap(
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)));
jPanel聊天面板.setLayout(new java.awt.BorderLayout());
jTextPane接收框.setEditable(false);
jScrollPane1.setViewportView(jTextPane接收框);
jPanel聊天面板.add(jScrollPane1, java.awt.BorderLayout.CENTER);
jPanel发送面板.setBackground(new java.awt.Color(204, 255, 255));
jButton发送.setText("\u53d1\u9001");
jButton发送.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton发送ActionPerformed(evt);
}
});
jButton关闭.setText("\u5173\u95ed");
jPanel工具面板.setBackground(new java.awt.Color(204, 255, 255));
jLabel字体.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_font_32.png"))); // NOI18N
jLabel字体.setToolTipText("\u5b57\u4f53");
jLabel字体.setBorder(javax.swing.BorderFactory.createEtchedBorder(
new java.awt.Color(204, 255, 255), new java.awt.Color(204, 255,
255)));
jLabel表情.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_face_32.png"))); // NOI18N
jLabel表情.setToolTipText("\u8868\u60c5");
jLabel图片.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_picture_32.png"))); // NOI18N
jLabel图片.setToolTipText("\u53d1\u9001\u56fe\u7247");
jLabel音乐.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_music_32.png"))); // NOI18N
jLabel音乐.setToolTipText("\u53d1\u9001\u97f3\u4e50");
jLabel截图.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_snap_32.png"))); // NOI18N
jLabel截图.setToolTipText("\u622a\u56fe");
jLabel聊天记录.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/client/img/chat/fun_message_history_32.png"))); // NOI18N
jLabel聊天记录.setText("\u804a\u5929\u8bb0\u5f55");
jLabel聊天记录
.setToolTipText("\u6253\u5f00\u6211\u7684\u804a\u5929\u8bb0\u5f55");
javax.swing.GroupLayout jPanel工具面板Layout = new javax.swing.GroupLayout(
jPanel工具面板);
jPanel工具面板.setLayout(jPanel工具面板Layout);
jPanel工具面板Layout
.setHorizontalGroup(jPanel工具面板Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
jPanel工具面板Layout
.createSequentialGroup()
.addContainerGap()
.addComponent(
jLabel字体,
javax.swing.GroupLayout.PREFERRED_SIZE,
36,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel表情)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel音乐)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel图片)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel截图)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED,
193, Short.MAX_VALUE)
.addComponent(jLabel聊天记录)));
jPanel工具面板Layout
.setVerticalGroup(jPanel工具面板Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
jPanel工具面板Layout
.createSequentialGroup()
.addGroup(
jPanel工具面板Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel字体)
.addComponent(jLabel表情)
.addComponent(jLabel音乐)
.addComponent(jLabel图片)
.addComponent(jLabel截图)
.addComponent(
jLabel聊天记录))
.addContainerGap()));
jScrollPane3.setViewportView(jTextPane发送框);
javax.swing.GroupLayout jPanel发送面板Layout = new javax.swing.GroupLayout(
jPanel发送面板);
jPanel发送面板.setLayout(jPanel发送面板Layout);
jPanel发送面板Layout
.setHorizontalGroup(jPanel发送面板Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel工具面板,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
jPanel发送面板Layout
.createSequentialGroup()
.addContainerGap(321, Short.MAX_VALUE)
.addComponent(
jButton关闭,
javax.swing.GroupLayout.PREFERRED_SIZE,
76,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(
jButton发送,
javax.swing.GroupLayout.PREFERRED_SIZE,
77,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(5, 5, 5))
.addComponent(jScrollPane3,
javax.swing.GroupLayout.DEFAULT_SIZE, 486,
Short.MAX_VALUE));
jPanel发送面板Layout
.setVerticalGroup(jPanel发送面板Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
jPanel发送面板Layout
.createSequentialGroup()
.addComponent(
jPanel工具面板,
javax.swing.GroupLayout.PREFERRED_SIZE,
36,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(
jScrollPane3,
javax.swing.GroupLayout.PREFERRED_SIZE,
96,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addGroup(
jPanel发送面板Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(
jButton发送,
javax.swing.GroupLayout.DEFAULT_SIZE,
35,
Short.MAX_VALUE)
.addComponent(
jButton关闭,
javax.swing.GroupLayout.DEFAULT_SIZE,
35,
Short.MAX_VALUE))
.addContainerGap()));
javax.swing.GroupLayout jPanel左侧面板Layout = new javax.swing.GroupLayout(
jPanel左侧面板);
jPanel左侧面板.setLayout(jPanel左侧面板Layout);
jPanel左侧面板Layout.setHorizontalGroup(jPanel左侧面板Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel顶部面板, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel发送面板, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel聊天面板, javax.swing.GroupLayout.DEFAULT_SIZE,
486, Short.MAX_VALUE));
jPanel左侧面板Layout
.setVerticalGroup(jPanel左侧面板Layout
.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
jPanel左侧面板Layout
.createSequentialGroup()
.addComponent(
jPanel顶部面板,
javax.swing.GroupLayout.PREFERRED_SIZE,
89,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(
jPanel聊天面板,
javax.swing.GroupLayout.DEFAULT_SIZE,
260, Short.MAX_VALUE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(
jPanel发送面板,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addComponent(jPanel左侧面板,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE)
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel右侧面板,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)));
layout.setVerticalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel右侧面板, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel左侧面板,
javax.swing.GroupLayout.Alignment.TRAILING,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
pack();
}// </editor-fold>
//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt)
{
// TODO add your handling code here:
beforeClose();
}
private void jLabel发送文件MouseClicked(java.awt.event.MouseEvent evt)
{
// TODO add your handling code here:
sendFile();
}
private void jButton发送ActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
sendMessage();
}
//GEN-BEGIN:variables
// Variables declaration - do not modify
private javax.swing.JButton jButton关闭;
public javax.swing.JButton jButton发送;
private javax.swing.JLabel jLabelQQ秀_对方;
private javax.swing.JLabel jLabelQQ秀_自己;
public javax.swing.JLabel jLabelQQ空间;
public javax.swing.JLabel jLabel加好友;
public javax.swing.JLabel jLabel发送文件;
public javax.swing.JLabel jLabel图片;
private javax.swing.JLabel jLabel头像;
public javax.swing.JLabel jLabel字体;
public javax.swing.JLabel jLabel我的好友;
public javax.swing.JLabel jLabel截图;
public javax.swing.JLabel jLabel聊天记录;
public javax.swing.JLabel jLabel表情;
public javax.swing.JLabel jLabel视频;
public javax.swing.JLabel jLabel语音;
public javax.swing.JLabel jLabel音乐;
private javax.swing.JPanel jPanel发送面板;
private javax.swing.JPanel jPanel右侧面板;
private javax.swing.JPanel jPanel左侧面板;
private javax.swing.JPanel jPanel聊天面板;
private javax.swing.JPanel jPanel顶部面板;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane3;
public javax.swing.JTextPane jTextPane发送框;
public javax.swing.JTextPane jTextPane接收框;
// End of variables declaration//GEN-END:variables
public javax.swing.JTextPane getjTextPane聊天记录()
{
return jTextPane接收框;
}
public void setjTextPane聊天记录(javax.swing.JTextPane jTextPane聊天记录)
{
this.jTextPane接收框 = jTextPane聊天记录;
}
/**
* 发送消息,空的方法,由子类实现
*/
public void sendMessage()
{
}
public void beforeClose(){}
/**
* 选择表情
*/
public void selectFace(){}
/**
* 处理消息中的表情
*/
public void dealIcon(String str)
{
}
/**
* 发送文件
*/
public void sendFile()
{
}
/**
* 发送图片
*/
public void sendImg()
{
}
public void screenFram()
{
}
}
================================================
FILE: src/client/frame/FaceFrame.java
================================================
package client.frame;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
import client.common.MyLabel;
import client.control.Chat;
public class FaceFrame extends JWindow
{
private JPanel contentPane;
GridLayout gridLayout1 = new GridLayout();
public static JLabel[] ico = new JLabel[90];
Chat chat;
int width=720;
int height=288;
public FaceFrame(Chat chat)
{
super(chat);
this.chat = chat;
try
{
jbInit();
int left=chat.getLocation().x+20;
int top=chat.getLocation().y+chat.getHeight()-200-height;
this.setBounds(left, top, width, height);
this.setAlwaysOnTop(true);
this.setVisible(true);
} catch (Exception exception)
{
exception.printStackTrace();
}
}
private void jbInit() throws Exception
{
getContentPane().setLayout(gridLayout1);
gridLayout1.setColumns(15);
gridLayout1.setHgap(1);
gridLayout1.setRows(6);
gridLayout1.setVgap(1);
String fileName = " ";
for (int i = 0; i < ico.length; i++)
{
if(i<10)
{
fileName= "/client/img/face/f00"+i+".png";//修改图片路径
}
else
{
fileName= "/client/img/face/f0"+i+".png";
}
ico[i]=new JLabel(new ImageIcon(FaceFrame.class.getResource(fileName)));
ico[i].setToolTipText("点此添加QQ表情哟^_^");
new MyLabel(ico[i],Color.black).addEvent();
final Icon img = ico[i].getIcon();
final int count=i;
ico[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
chat.jTextPane发送框.insertIcon(img);
chat.faceIdx=count;
getObj().dispose();// 这里最好用单例模式
}
});
this.getContentPane().add(ico[i]);
}
this.getContentPane().setBackground(SystemColor.text);
}
private JWindow getObj()
{
return this;
}
}
================================================
FILE: src/client/frame/LoginFrame.java
================================================
package client.frame;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import client.frame.MyPanel;
import javax.swing.JLabel;
//import com.sun.awt.AWTUtilities;
import javax.swing.JPasswordField;
import javax.swing.JComboBox;
import java.awt.Font;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JTextField;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class LoginFrame extends JFrame
{
private JPanel contentPane;
public JPasswordField pwd密码;
private JLabel lblQQ2013;
public JLabel lbl头像;
public JCheckBox checkBox记住密码;
public JCheckBox checkBox自动登录;
public JLabel lbl登录;
public JTextField textField用户名;
public JLabel lbl注册账号;
public JLabel lbl忘记密码;
public JLabel lbl最小化;
public JLabel lbl退出;
public JLabel lbl多账号;
public JLabel lbl设置;
public JComboBox comboBox状态;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
LoginFrame frame = new LoginFrame();
//AWTUtilities.setWindowOpaque(frame, false);//设置窗体完全透明
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LoginFrame()
{
setTitle("QQ2013");
setIconImage(Toolkit.getDefaultToolkit().getImage(LoginFrame.class.getResource("/client/img/QQ_64.png")));
setUndecorated(true);//设置窗体没有边框
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 354, 272);
contentPane = new MyPanel("../img/QQ2011_Login.png");
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
pwd密码 = new JPasswordField();
pwd密码.setText("123");
pwd密码.setEchoChar('●');
pwd密码.setBounds(104, 163, 154, 26);
contentPane.add(pwd密码);
lblQQ2013 = new JLabel("QQ2013");
lblQQ2013.setForeground(new Color(0, 0, 51));
lblQQ2013.setFont(new Font("宋体", Font.BOLD, 16));
lblQQ2013.setBounds(14, 6, 55, 18);
contentPane.add(lblQQ2013);
lbl头像 = new JLabel("");
lbl头像.setIcon(new ImageIcon(LoginFrame.class.getResource("/client/img/headImage/head_boy_01_64.jpg")));
lbl头像.setBounds(18, 127, 64, 64);
contentPane.add(lbl头像);
checkBox记住密码 = new JCheckBox("\u8BB0\u4F4F\u5BC6\u7801");
checkBox记住密码.setBounds(156, 198, 76, 18);
contentPane.add(checkBox记住密码);
checkBox自动登录 = new JCheckBox("\u81EA\u52A8\u767B\u5F55");
checkBox自动登录.setBounds(237, 198, 76, 18);
contentPane.add(checkBox自动登录);
lbl登录 = new JLabel("");
lbl登录.setIcon(new ImageIcon(LoginFrame.class.getResource("/client/img/button/button_login_1.png")));
lbl登录.setBounds(262, 237, 69, 22);
contentPane.add(lbl登录);
textField用户名 = new JTextField();
textField用户名.setText("\u9A6C\u5316\u817E");
textField用户名.setBounds(104, 128, 154, 26);
contentPane.add(textField用户名);
textField用户名.setColumns(10);
lbl注册账号 = new JLabel("\u6CE8\u518C\u8D26\u53F7");
lbl注册账号.setFont(new Font("SansSerif", Font.PLAIN, 13));
lbl注册账号.setForeground(new Color(0, 51, 255));
lbl注册账号.setBounds(288, 132, 55, 18);
contentPane.add(lbl注册账号);
lbl忘记密码 = new JLabel("\u5FD8\u8BB0\u5BC6\u7801");
lbl忘记密码.setFont(new Font("SansSerif", Font.PLAIN, 13));
lbl忘记密码.setForeground(new Color(0, 51, 255));
lbl忘记密码.setBounds(288, 167, 55, 18);
contentPane.add(lbl忘记密码);
lbl最小化 = new JLabel("");
lbl最小化.setIcon(new ImageIcon(LoginFrame.class.getResource("/client/img/button/login_minsize_1.png")));
lbl最小化.setBounds(284, 0, 29, 19);
contentPane.add(lbl最小化);
lbl退出 = new JLabel("");
lbl退出.setIcon(new ImageIcon(LoginFrame.class.getResource("/client/img/button/login_exit_1.png")));
lbl退出.setBounds(312, -1, 37, 20);
contentPane.add(lbl退出);
lbl多账号 = new JLabel("");
lbl多账号.setIcon(new ImageIcon(LoginFrame.class.getResource("/client/img/button/login_duozhanghao_1.png")));
lbl多账号.setBounds(14, 237, 69, 21);
contentPane.add(lbl多账号);
lbl设置 = new JLabel("");
lbl设置.setIcon(new ImageIcon(LoginFrame.class.getResource("/client/img/button/login_setting_1.png")));
lbl设置.setBounds(93, 237, 69, 21);
contentPane.add(lbl设置);
comboBox状态 = new JComboBox();
comboBox状态.setBounds(104, 195, 40, 24);
contentPane.add(comboBox状态);
}
}
================================================
FILE: src/client/frame/MainFrame.java
================================================
package client.frame;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Toolkit;
import java.awt.Color;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JOptionPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import java.awt.Font;
import javax.swing.JTabbedPane;
import javax.swing.JButton;
import javax.swing.JToolBar;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import javax.swing.JTree;
import javax.swing.JScrollPane;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPopupMenu;
import java.awt.Component;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
* @author LXA
*
*/
public class MainFrame extends JFrame
{
public JLabel lbl设置;
public JLabel lbl头像;
public JComboBox comboBox状态;
public JLabel lbl用户名;
public JLabel lbl个性签名;
public JTree tree;
private JTabbedPane tabbedPane;
private JPanel panel好友列表;
private JPanel panel群;
private JPanel panel最近;
private JScrollPane scrollPane好友;
private JPanel panel用户信息;
private JPanel panel好友面板;
private JPanel panel设置面板;
private JPopupMenu popupMenu好友列表;
private JMenuItem menuItem发送即时消息;
private JMenuItem menuItem查看好友信息;
private JMenuItem menuItem发送文件;
private JMenuItem menuItem删除用户;
/**
* Create the frame.
*/
public MainFrame()
{
setIconImage(Toolkit.getDefaultToolkit().getImage(MainFrame.class.getResource("/client/img/QQ_64.png")));
setTitle("QQ2013");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 330, 600);
panel用户信息 = new JPanel();
panel用户信息.setBackground(new Color(51, 153, 255));
panel好友面板 = new JPanel();
panel设置面板 = new JPanel();
panel设置面板.setBackground(new Color(51, 153, 255));
GroupLayout groupLayout = new GroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel用户信息, GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
.addComponent(panel设置面板, GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
.addComponent(panel好友面板, GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(panel用户信息, GroupLayout.PREFERRED_SIZE, 96, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel好友面板, GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel设置面板, GroupLayout.PREFERRED_SIZE, 75, GroupLayout.PREFERRED_SIZE))
);
panel好友面板.setLayout(new BorderLayout(0, 0));
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
panel好友面板.add(tabbedPane, BorderLayout.CENTER);
panel好友列表 = new JPanel();
tabbedPane.addTab("\u597D\u53CB", new ImageIcon(MainFrame.class.getResource("/client/img/friend_list.png")), panel好友列表, null);
panel好友列表.setLayout(new BorderLayout(0, 0));
scrollPane好友 = new JScrollPane();
panel好友列表.add(scrollPane好友);
tree = new JTree();
scrollPane好友.setViewportView(tree);
popupMenu好友列表 = new JPopupMenu();
addPopup(tree, popupMenu好友列表);
menuItem发送即时消息 = new JMenuItem("\u53D1\u9001\u5373\u65F6\u6D88\u606F");
menuItem发送即时消息.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
startChat(e);
}
});
menuItem发送即时消息.setIcon(new ImageIcon(MainFrame.class.getResource("/client/img/QQ_16.png")));
popupMenu好友列表.add(menuItem发送即时消息);
menuItem发送文件 = new JMenuItem("\u53D1\u9001\u6587\u4EF6");
menuItem发送文件.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
sendFile(e);
}
});
popupMenu好友列表.add(menuItem发送文件);
menuItem查看好友信息 = new JMenuItem("\u67E5\u770B\u597D\u53CB\u8D44\u6599");
menuItem查看好友信息.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
getFriendInfo(e);
}
});
popupMenu好友列表.add(menuItem查看好友信息);
menuItem删除用户 = new JMenuItem("\u5220\u9664\u7528\u6237");
menuItem删除用户.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
deleteFriend(e);
}
});
popupMenu好友列表.add(menuItem删除用户);
panel群 = new JPanel();
tabbedPane.addTab("\u7FA4\u7EC4", new ImageIcon(MainFrame.class.getResource("/client/img/friend_qun.png")), panel群, null);
JButton btn官方聊天室 = new JButton("\u8FDB\u5165\u5B98\u65B9\u804A\u5929\u5BA4");
btn官方聊天室.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
gotoChatRoom();
}
});
btn官方聊天室.setFont(new Font("微软雅黑", Font.PLAIN, 28));
JButton btn新建聊天室 = new JButton("\u65B0\u5EFA\u804A\u5929\u5BA4");
btn新建聊天室.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
buildNewChatRoom();
}
});
btn新建聊天室.setFont(new Font("微软雅黑", Font.PLAIN, 28));
GroupLayout gl_panel群 = new GroupLayout(panel群);
gl_panel群.setHorizontalGroup(
gl_panel群.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_panel群.createSequentialGroup()
.addContainerGap()
.addGroup(gl_panel群.createParallelGroup(Alignment.TRAILING)
.addComponent(btn新建聊天室, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE)
.addComponent(btn官方聊天室, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE))
.addContainerGap())
);
gl_panel群.setVerticalGroup(
gl_panel群.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel群.createSequentialGroup()
.addContainerGap()
.addComponent(btn官方聊天室, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btn新建聊天室, GroupLayout.PREFERRED_SIZE, 76, GroupLayout.PREFERRED_SIZE)
.addContainerGap(132, Short.MAX_VALUE))
);
panel群.setLayout(gl_panel群);
panel最近 = new JPanel();
tabbedPane.addTab("\u6700\u8FD1", new ImageIcon(MainFrame.class.getResource("/client/img/friend_history.png")), panel最近, null);
panel设置面板.setLayout(null);
lbl设置 = new JLabel("");
lbl设置.setIcon(new ImageIcon(MainFrame.class.getResource("/client/img/button/QQ_settings_1.png")));
lbl设置.setBounds(6, 6, 64, 64);
panel设置面板.add(lbl设置);
panel用户信息.setLayout(null);
lbl头像 = new JLabel("");
lbl头像.setIcon(new ImageIcon(MainFrame.class.getResource("/client/img/headImage/head_boy_01_64.jpg")));
lbl头像.setBounds(15, 15, 64, 64);
panel用户信息.add(lbl头像);
comboBox状态 = new JComboBox();
comboBox状态.setBounds(91, 15, 58, 28);
panel用户信息.add(comboBox状态);
lbl用户名 = new JLabel("\u9A6C\u5316\u817E");
lbl用户名.setFont(new Font("黑体", Font.BOLD, 18));
lbl用户名.setBounds(159, 18, 90, 25);
panel用户信息.add(lbl用户名);
lbl个性签名 = new JLabel("\u5404\u4F4D\u817E\u8BAF\u7F51\u53CB\u597D\uFF0CQQ2013\u5373\u5C06\u516C\u6D4B\u4E86");
lbl个性签名.setBounds(91, 55, 210, 18);
panel用户信息.add(lbl个性签名);
getContentPane().setLayout(groupLayout);
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
/**
* 开始聊天
*/
public void startChat(ActionEvent e)
{
}
/**
* 获取好友资料
* @param e
*/
public void getFriendInfo(ActionEvent e)
{
}
/**
* 发送文件
* @param e
*/
public void sendFile(ActionEvent e)
{
}
/**
* 删除好友
* @param e
*/
public void deleteFriend(ActionEvent e)
{
}
/**
* 进入聊天室
*/
public void gotoChatRoom()
{}
/**
* 新建聊天室
*/
public void buildNewChatRoom()
{
}
}
/*TreePath path =tree.getSelectionPath();
if (path.getPathCount()>1) //选择的不是根节点
{
System.out.println(path);
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
DefaultTreeModel treeModel= (DefaultTreeModel) tree.getModel();
treeModel.removeNodeFromParent(node);
} */
================================================
FILE: src/client/frame/MyPanel.java
================================================
package client.frame;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
import com.MyTools;
public class MyPanel extends JPanel
{
private Image image=null;
public MyPanel(String imagePath)
{
this.setOpaque(false);
image=MyTools.getIcon(imagePath).getImage();
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
================================================
FILE: src/client/frame/PublicMessageFrame.java
================================================
package client.frame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import javax.swing.ImageIcon;
import client.common.MyLabel;
import client.control.Chat;
import javax.swing.JScrollPane;
public class PublicMessageFrame extends JDialog
{
private JPanel contentPane;
public JTextArea textArea公告;
public JLabel lbl关闭;
private JLabel lbl最小化;
public JButton btn打开 ;
public Chat chat=null;
private JScrollPane scrollPane;
/**
* Launch the application.
*/
public static void main(String[] args)
{
new PublicMessageFrame("您有未读消息","大家好,这里是腾讯公司!仿盛大发撒发的发生的发",null);
}
/**
* @wbp.parser.constructor
*/
public PublicMessageFrame(String title,String publicMessage)
{
init(title, publicMessage);
}
/**
* Create the frame.
*/
public PublicMessageFrame(String title,String publicMessage,Chat chat)
{
this.chat=chat;
init(title, publicMessage);
}
public void init(String title,String publicMessage)
{
setUndecorated(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 352, 267);
contentPane = new MyPanel("../img/QQ2011_Login.png");
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lbl标题 = new JLabel(title);
lbl标题.setFont(new Font("宋体", Font.BOLD, 16));
lbl标题.setBounds(15, 5, 237, 21);
contentPane.add(lbl标题);
JButton btn关闭 = new JButton("\u5173\u95ED(C)");
btn关闭.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
dispose();
}
});
btn关闭.setBounds(247, 234, 83, 27);
contentPane.add(btn关闭);
scrollPane = new JScrollPane();
scrollPane.setBounds(1, 107, 345, 126);
contentPane.add(scrollPane);
textArea公告 = new JTextArea();
scrollPane.setViewportView(textArea公告);
textArea公告.setLineWrap(true);
textArea公告.setFont(new Font("微软雅黑", Font.BOLD, 18));
textArea公告.setBackground(new Color(255, 250, 250));
textArea公告.setEditable(false);
textArea公告.setText(publicMessage);
lbl关闭 = new JLabel("");
lbl关闭.setIcon(new ImageIcon(PublicMessageFrame.class.getResource("/client/img/button/login_exit_1.png")));
lbl关闭.setBounds(312, 0, 38, 18);
contentPane.add(lbl关闭);
lbl最小化 = new JLabel("");
lbl最小化.setIcon(new ImageIcon(PublicMessageFrame.class.getResource("/client/img/button/login_minsize_1.png")));
lbl最小化.setBounds(282, 0, 29, 18);
contentPane.add(lbl最小化);
btn打开 = new JButton("\u6253\u5F00");
btn打开.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
showChat();
}
});
btn打开.setBounds(165, 234, 83, 27);
contentPane.add(btn打开);
addEvent();
showFrame();
}
/**
* 添加事件
*/
public void addEvent()
{
new MyLabel(lbl最小化, "../img/button/login_minsize", "png").addEvent();
new MyLabel(lbl关闭, "../img/button/login_exit", "png").addEvent();
lbl关闭.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
dispose();
}
});
}
/**
* 显示窗体
*/
public void showFrame()
{
this.setAlwaysOnTop(true);
if(chat==null)
btn打开.setVisible(false);
int width=350;
int height=266;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(screenSize.width-width-3,screenSize.height,width,height);
setVisible(true);
Timer timer=new Timer(10, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
setLocation(getLocation().x, getLocation().y-10);
}
});
timer.start();
while(true)
{
// 25表示任务栏的高度,好奇怪,有的电脑注释掉下面的输出语句就会出现弹窗不停止的奇怪现象
System.out.println("当前高度:"+getLocation().y+",屏幕高度:"+screenSize.height);
if(getLocation().y+height<screenSize.height-25)
{
timer.stop();
break;
}
}
}
/**
* 显示聊天窗体
*/
public void showChat()
{
if(chat!=null)
{
chat.setVisible(true);
this.dispose();
}
}
}
================================================
FILE: src/client/frame/QunChatFrame.java
================================================
package client.frame;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.Color;
import javax.swing.border.EtchedBorder;
import javax.swing.UIManager;
import javax.swing.border.CompoundBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextPane;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
public class QunChatFrame extends JFrame
{
private JPanel contentPane;
public JTree tree;
public JButton btn发送;
public JButton btn关闭;
public JTextPane textPane发送;
public JTextPane textPane接收框;
public JTextArea textArea群公告;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
QunChatFrame frame = new QunChatFrame();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public QunChatFrame()
{
setTitle("MyQQ\u5B98\u65B9\u804A\u5929\u5BA4");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 712, 576);
contentPane = new JPanel();
contentPane.setBackground(new Color(0, 153, 255));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JPanel panel右边 = new JPanel();
JPanel panel左边 = new JPanel();
panel左边.setBackground(new Color(204, 255, 204));
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
.addComponent(panel左边, GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel右边, GroupLayout.PREFERRED_SIZE, 203, GroupLayout.PREFERRED_SIZE))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(panel右边, GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)
.addComponent(panel左边, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 493, Short.MAX_VALUE)
);
JPanel panel顶部 = new JPanel();
panel顶部.setBackground(new Color(0, 153, 255));
JPanel panel中间 = new JPanel();
JPanel panel底部 = new JPanel();
panel底部.setBackground(new Color(204, 255, 255));
GroupLayout gl_panel左边 = new GroupLayout(panel左边);
gl_panel左边.setHorizontalGroup(
gl_panel左边.createParallelGroup(Alignment.LEADING)
.addComponent(panel底部, GroupLayout.PREFERRED_SIZE, 476, Short.MAX_VALUE)
.addComponent(panel顶部, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
.addComponent(panel中间, GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
);
gl_panel左边.setVerticalGroup(
gl_panel左边.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel左边.createSequentialGroup()
.addComponent(panel顶部, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel中间, GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel底部, GroupLayout.PREFERRED_SIZE, 196, GroupLayout.PREFERRED_SIZE))
);
panel顶部.setLayout(null);
JLabel lbl头像 = new JLabel("");
lbl头像.setIcon(new ImageIcon(QunChatFrame.class.getResource("/client/img/QQ_64.png")));
lbl头像.setBounds(6, 6, 64, 64);
panel顶部.add(lbl头像);
JLabel lbl视频 = new JLabel("");
lbl视频.setIcon(new ImageIcon(QunChatFrame.class.getResource("/client/img/chat/fun_video_54.png")));
lbl视频.setBounds(82, 16, 54, 54);
panel顶部.add(lbl视频);
JLabel lbl语音 = new JLabel("");
lbl语音.setIcon(new ImageIcon(QunChatFrame.class.getResource("/client/img/chat/fun_voice_54.png")));
lbl语音.setBounds(138, 16, 54, 54);
panel顶部.add(lbl语音);
JLabel lbl发送文件 = new JLabel("");
lbl发送文件.setIcon(new ImageIcon(QunChatFrame.class.getResource("/client/img/chat/fun_sendfile_54.png")));
lbl发送文件.setBounds(193, 16, 54, 54);
panel顶部.add(lbl发送文件);
panel中间.setLayout(new BorderLayout(0, 0));
textPane接收框 = new JTextPane();
panel中间.add(textPane接收框);
textPane发送 = new JTextPane();
btn发送 = new JButton("\u53D1\u9001");
btn发送.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 18));
btn关闭 = new JButton("\u5173\u95ED");
btn关闭.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 18));
JLabel lbl文字 = new JLabel("");
lbl文字.setIcon(new ImageIcon(QunChatFrame.class.getResource("/client/img/chat/fun_font_32.png")));
JLabel lbl表情 = new JLabel("");
lbl表情.setIcon(new ImageIcon(QunChatFrame.class.getResource("/client/img/chat/fun_face_32.png")));
JLabel lbl音乐 = new JLabel("");
lbl音乐.setIcon(new ImageIcon(QunChatFrame.class.getResource("/client/img/chat/fun_music_32.png")));
JLabel lbl图片 = new JLabel("");
lbl图片.setIcon(new ImageIcon(QunChatFrame.class.getResource("/client/img/chat/fun_picture_32.png")));
JLabel lbl截图 = new JLabel("");
lbl截图.setIcon(new ImageIcon(QunChatFrame.class.getResource("/client/img/chat/fun_snap_32.png")));
GroupLayout gl_panel底部 = new GroupLayout(panel底部);
gl_panel底部.setHorizontalGroup(
gl_panel底部.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel底部.createSequentialGroup()
.addContainerGap(285, Short.MAX_VALUE)
.addComponent(btn关闭, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btn发送, GroupLayout.PREFERRED_SIZE, 86, GroupLayout.PREFERRED_SIZE)
.addGap(15))
.addComponent(textPane发送, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
.addGroup(Alignment.LEADING, gl_panel底部.createSequentialGroup()
.addContainerGap()
.addComponent(lbl文字)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(lbl表情)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(lbl音乐)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(lbl图片)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(lbl截图)
.addContainerGap(258, Short.MAX_VALUE))
);
gl_panel底部.setVerticalGroup(
gl_panel底部.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_panel底部.createSequentialGroup()
.addContainerGap(24, Short.MAX_VALUE)
.addGroup(gl_panel底部.createParallelGroup(Alignment.LEADING)
.addComponent(lbl文字)
.addComponent(lbl表情)
.addComponent(lbl音乐)
.addComponent(lbl图片)
.addComponent(lbl截图))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textPane发送, GroupLayout.PREFERRED_SIZE, 88, GroupLayout.PREFERRED_SIZE)
.addGap(18)
.addGroup(gl_panel底部.createParallelGroup(Alignment.LEADING, false)
.addComponent(btn发送, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn关闭, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
panel底部.setLayout(gl_panel底部);
panel左边.setLayout(gl_panel左边);
JPanel panel公告 = new JPanel();
panel公告.setBackground(new Color(0, 153, 255));
panel公告.setBorder(new TitledBorder(null, "\u7FA4\u516C\u544A", TitledBorder.LEADING, TitledBorder.ABOVE_TOP, null, Color.RED));
JScrollPane scrollPane = new JScrollPane();
panel公告.setLayout(new BorderLayout(0, 0));
textArea群公告 = new JTextArea();
textArea群公告.setLineWrap(true);
textArea群公告.setForeground(new Color(255, 0, 0));
textArea群公告.setText("\u6682\u65E0\u4EFB\u4F55\u5B98\u65B9\u516C\u544A\uFF01");
textArea群公告.setFont(new Font("微软雅黑", Font.BOLD, 18));
textArea群公告.setBackground(new Color(255, 204, 0));
textArea群公告.setEnabled(false);
panel公告.add(textArea群公告, BorderLayout.CENTER);
GroupLayout gl_panel右边 = new GroupLayout(panel右边);
gl_panel右边.setHorizontalGroup(
gl_panel右边.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel右边.createSequentialGroup()
.addGap(0)
.addGroup(gl_panel右边.createParallelGroup(Alignment.LEADING)
.addComponent(panel公告, GroupLayout.PREFERRED_SIZE, 203, GroupLayout.PREFERRED_SIZE)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE))
.addGap(0))
);
gl_panel右边.setVerticalGroup(
gl_panel右边.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel右边.createSequentialGroup()
.addComponent(panel公告, GroupLayout.PREFERRED_SIZE, 170, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE))
);
tree = new JTree();
tree.setRootVisible(false);
scrollPane.setViewportView(tree);
panel右边.setLayout(gl_panel右边);
contentPane.setLayout(gl_contentPane);
}
}
================================================
FILE: src/client/frame/RegisterFrame.java
================================================
package client.frame;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.JToggleButton;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.border.CompoundBorder;
import client.control.Login;
import client.control.Register;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class RegisterFrame extends JFrame {
public JPanel contentPane;
public JTextField txtName;
public JPasswordField pwd;
public JPasswordField pwdRe;
public JTextField txtEmail;
public JTextField txtbirthday;
public JComboBox comGender;
public JTextArea txtSignat;//签名
public JComboBox comboBoxHeadImage;//头像
public JButton btnRegister;
/**
* Create the frame.
*/
public RegisterFrame()
{
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
beforeClose();
}
});
setIconImage(Toolkit.getDefaultToolkit().getImage(RegisterFrame.class.getResource("/client/img/QQ_64.png")));
setTitle("QQ2013\u6CE8\u518C");
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setSize(592, 553);
contentPane = new MyPanel("../img/registerBGimg.jpg");
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lbUserName = new JLabel("\u7528\u6237\u540D");
lbUserName.setFont(new Font("微软雅黑", Font.PLAIN, 18));
lbUserName.setBounds(38, 45, 54, 24);
contentPane.add(lbUserName);
JLabel lbPwd = new JLabel("\u5BC6\u7801");
lbPwd.setFont(new Font("微软雅黑", Font.PLAIN, 18));
lbPwd.setBounds(38, 96, 54, 30);
contentPane.add(lbPwd);
JLabel lbPwdre = new JLabel("\u91CD\u590D\u5BC6\u7801");
lbPwdre.setFont(new Font("微软雅黑", Font.PLAIN, 18));
lbPwdre.setBounds(22, 138, 79, 35);
contentPane.add(lbPwdre);
JLabel lbEmail = new JLabel("E-mail");
lbEmail.setFont(new Font("微软雅黑", Font.PLAIN, 18));
lbEmail.setBounds(33, 234, 59, 28);
contentPane.add(lbEmail);
JLabel lbBirthday = new JLabel("\u751F\u65E5");
lbBirthday.setFont(new Font("微软雅黑", Font.PLAIN, 18));
lbBirthday.setBounds(38, 285, 46, 24);
contentPane.add(lbBirthday);
JLabel lbSignature = new JLabel("\u4E2A\u6027\u7B7E\u540D");
lbSignature.setFont(new Font("微软雅黑", Font.PLAIN, 18));
lbSignature.setBounds(22, 332, 79, 28);
contentPane.add(lbSignature);
btnRegister = new JButton("\u514D\u8D39\u6CE8\u518C");
btnRegister.setForeground(new Color(255, 255, 255));
btnRegister.setBackground(new Color(0, 100, 0));
btnRegister.setFont(new Font("微软雅黑", Font.BOLD, 28));
btnRegister.setBounds(57, 431, 161, 60);
contentPane.add(btnRegister);
JButton btnCancel = new JButton("\u53D6\u6D88");
btnCancel.setForeground(new Color(255, 250, 250));
btnCancel.setBackground(new Color(106, 90, 205));
btnCancel.setFont(new Font("微软雅黑", Font.BOLD, 28));
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
cancle();
}
});
btnCancel.setBounds(248, 431, 100, 60);
contentPane.add(btnCancel);
txtName = new JTextField();
txtName.setBounds(111, 40, 217, 35);
contentPane.add(txtName);
txtName.setColumns(10);
pwd = new JPasswordField();
pwd.setBounds(111, 92, 217, 35);
contentPane.add(pwd);
pwdRe = new JPasswordField();
pwdRe.setBounds(113, 138, 215, 35);
contentPane.add(pwdRe);
txtEmail = new JTextField();
txtEmail.setColumns(10);
txtEmail.setBounds(111, 231, 217, 35);
contentPane.add(txtEmail);
comGender = new JComboBox();
comGender.setModel(new DefaultComboBoxModel(new String[] {"男", "女"}));
comGender.setBounds(111, 185, 59, 35);
contentPane.add(comGender);
JLabel lbGender = new JLabel("\u6027\u522B");
lbGender.setFont(new Font("微软雅黑", Font.PLAIN, 18));
lbGender.setBounds(38, 190, 46, 24);
contentPane.add(lbGender);
txtSignat = new JTextArea();
txtSignat.setBounds(111, 328, 217, 75);
contentPane.add(txtSignat);
txtbirthday = new JTextField();
txtbirthday.setBounds(111, 281, 217, 35);
contentPane.add(txtbirthday);
txtbirthday.setColumns(10);
comboBoxHeadImage = new JComboBox();
comboBoxHeadImage.setBounds(375, 193, 138, 117);
contentPane.add(comboBoxHeadImage);
JLabel lblHead = new JLabel("\u5934\u50CF\u9009\u62E9\uFF1A");
lblHead.setFont(new Font("微软雅黑", Font.PLAIN, 18));
lblHead.setBounds(375, 139, 100, 32);
contentPane.add(lblHead);
}
/**
* 在窗体关闭之前需要做的事
*/
public void beforeClose()
{}
/**
* 取消按钮事件
*/
public void cancle()
{}
}
================================================
FILE: src/client/frame/ScreenFram.java
================================================
package client.frame;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.filechooser.FileSystemView;
/**
* java截屏 运行后将当前屏幕截取,并最大化显示。 拖拽鼠标,选择自己需要的部分。 按Esc键保存图片到桌面,并退出程序。
* 点击右上角(没有可见的按钮),退出程序,不保存图片。
*
* @author JinCeon
*/
public class ScreenFram
{
public static void main()
{
// 全屏运行
RectD rd = new RectD();
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice();
gd.setFullScreenWindow(rd);
System.out.println("main方法中的截图名:"+ rd.name);
//return rd.name;
}
}
class RectD extends JFrame
{
private static final long serialVersionUID = 1L;
int orgx, orgy, endx, endy;
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
BufferedImage image;
BufferedImage tempImage;
BufferedImage saveImage;
Graphics g;
public String name;
@Override
public void paint(Graphics g)
{
RescaleOp ro = new RescaleOp(0.8f, 0, null);
tempImage = ro.filter(image, null);
g.drawImage(tempImage, 0, 0, this);
}
public RectD()
{
snapshot();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
endx = e.getX();
endy = e.getY();
g = getGraphics();
g.drawImage(tempImage, 0, 0, RectD.this);
int x = Math.min(orgx, endx);
int y = Math.min(orgy, endy);
int width = Math.abs(endx - orgx) + 1;
int height = Math.abs(endy - orgy) + 1;
// 加上1,防止width或height为0
g.setColor(Color.BLUE);
g.drawRect(x - 1, y - 1, width + 1, height + 1);
// 减1,加1都是为了防止图片将矩形框覆盖掉
saveImage = image.getSubimage(x, y, width, height);
g.drawImage(saveImage, x, y, RectD.this);
}
});
this.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
orgx = e.getX();
orgy = e.getY();
}
public void mouseReleased(MouseEvent e)
{
saveToFile();
dispose();
}
});
}
public void saveToFile()
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");
name ="snap";
//sdf.format(new Date());
// setName(sdf.format(new Date()));
String path = "./screenCut/";
String format = "jpg";
File f = new File(path, name + "." + format);
try
{
ImageIO.write(saveImage, format, f);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void snapshot()
{
try
{
Robot robot = new Robot();
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
image = robot.createScreenCapture(new Rectangle(0, 0, d.width,
d.height));
}
catch (AWTException e)
{
}
}
}
================================================
FILE: src/client/frame/SendFileFrame.java
================================================
package client.frame;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import client.control.RecieveThread;
import client.control.SendTread;
public class SendFileFrame extends JFrame
{
public JPanel contentPane;
public JLabel lbl;
public JProgressBar progressBar;
public JLabel lblProgress;
public RecieveThread recieveThread;
/**
* Create the frame.
*/
public SendFileFrame()
{
//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 510, 196);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lbl = new JLabel("进度条");
lbl.setBounds(42, 35, 74, 33);
contentPane.add(lbl);
progressBar = new JProgressBar();
progressBar.setForeground(Color.BLUE);
progressBar.setBounds(96, 35, 332, 33);
contentPane.add(progressBar);
lblProgress = new JLabel("");
lblProgress.setBounds(64, 82, 386, 58);
contentPane.add(lblProgress);
}
/**
* @param bar
* @param passlen
* @param sumlen
* @param lbl
*/
public void updateProgressBar(JProgressBar bar, long passlen, long sumlen,
JLabel lbl, double passTime)
{
int percent = (int) (passlen * 100 / sumlen);
bar.setValue(percent);
if (lbl != null)
{
String msg = "正在接受文件....." + (passlen / 1024) + "kb" + " /"
+ (sumlen / 1024) + "kb" + "已接收 "+ percent + "%"
+ "\n 发射点" + (int) ((passlen / 1024) / (passTime / 1000))
+ "Kb/s";
if (passlen == sumlen)
msg = "传输完毕!";
lblProgress.setText(msg);
}
}
/**
* @param seletMode
* @return
*/
public String showDialog(int seletMode)
{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(seletMode);
chooser.setMultiSelectionEnabled(true);//璁剧疆澶氶?鏂囦欢
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION)
{
String filePath = chooser.getSelectedFile().getAbsolutePath();
return filePath;
}
return null;
}
}
================================================
FILE: src/client/socket/CC_TCP.java
================================================
package client.socket;
import java.text.DateFormat;
import java.util.Date;
import client.common.MyTextPane;
import client.control.Chat;
import com.MyTools;
import com.MyTools.Flag;
import com.socket.TCP;
/**
* @author 刘显安
*客户端与客户端之间的TCP连接
*/
public class CC_TCP extends TCP
{
Chat chat=null;
public CC_TCP(String serverIP, int serverPort,Chat chat) throws Exception
{
super(serverIP, serverPort);
this.chat=chat;
}
@Override
public void dealWithMessage(Flag flag, String message)
{
switch (flag)
{
case MESSAGE:showMessage(message);break;
case SENDFILE:doStartSendFile(message);break;
case FACE:doFace(message);break;
default:break;
}
}
@Override
public void dealWithExit()
{
}
public void showMessage(String message)
{
chat.setReceivePaneText(false, message);
}
public void doStartSendFile(String message)
{
chat.friendGetFilePort=Integer.parseInt(message);
System.out.println("已成功获取好友的接收文件端口:"+message);
}
public void doFace(String message)
{
new MyTextPane(chat.jTextPane接收框).addIcon(MyTools.getFaceByIdx(Integer.parseInt(message)), chat.friendName);
}
}
================================================
FILE: src/client/socket/CS_TCP.java
================================================
package client.socket;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import client.control.Chat;
import client.control.Login;
import client.control.Main;
import client.control.SendTread;
import client.frame.PublicMessageFrame;
import client.frame.SendFileFrame;
import com.MyTools;
import com.MyTools.Flag;
import com.socket.TCP;
/**
* @author 刘显安
* 客户端与QQ服务器之间的TCP通讯
*/
public class CS_TCP extends TCP
{
Login login = null;//登录窗体,从构造方法中传过来
Main main=null;//主窗体
public CS_TCP(String serverIP, int serverPort, Login login,Main main) throws Exception
{
super(serverIP, serverPort);
this.login = login;
this.main=main;
}
/**
* 此构造方法仅供注册用
* @param serverIP
* @param serverPort
* @throws Exception
*/
public CS_TCP(String serverIP, int serverPort) throws Exception
{
super(serverIP, serverPort);
}
@Override
public void dealWithMessage(Flag flag, String message)
{
System.out.println("测试"+flag.toString()+","+message);
switch(flag)
{
case LOGIN:doLogin(message);break;//如果是登录
case REGISTER:doRegister(message);break;//如果是注册
case USERINFO:doUsersInfo(message);break;//如果是用户信息
case GET_FRIEND_INFO:doGetFriendInfo(message);break;//如果是服务器发来的指定好友信息
case FRIENDS_LIST:doFriendList(message);break;//接收服务器发来的刷新好友列表信息
case QUN_CHAT:doQunChat(message);break;//处理群消息
case PUBLIC_MESSAGE:doPublicMessage(message);break;//处理公告信息
case SHOW_WINDOW:doShowWindow(message);break;//处理公告信息
case UNDERLINE_MESSAGE:doUnreadMessage(message);break;//接收服务器发来的未读消息
default:break;
}
}
@Override
public void dealWithExit()
{
}
/**
* 处理与登录相关的事情
* @param message
*/
public void doLogin(String message)
{
//注意一定要给Flag加toString()
if (message.split(MyTools.SPLIT1)[0].equals(Flag.SUCCESS.toString()))// 如果登录成功
{
login.dispose();//销毁登录窗体
main.setCS_TCP(login.cs_TCP);
main.setVisible(true);
doUsersInfo(message.split(MyTools.SPLIT1)[1]);
}
else if (message.split(MyTools.SPLIT1)[0].equals(Flag.FAILED.toString()))// 如果登录失败
{
JOptionPane.showMessageDialog(null,
message.split(MyTools.SPLIT1)[1]);//显示登录失败的原因
}
}
public void doRegister(String message)
{
if(message.split(MyTools.SPLIT1)[0].equals(Flag.SUCCESS.toString()))
JOptionPane.showMessageDialog(null,message.split(MyTools.SPLIT1)[1]);
else if(message.split(MyTools.SPLIT1)[0].equals(Flag.FAILED.toString()))
JOptionPane.showMessageDialog(null, message.split(MyTools.SPLIT1)[1],"失败",JOptionPane.ERROR_MESSAGE);
}
/**
* 处理服务器发回来用户信息
* @param message
*/
public void doUsersInfo(String message)
{
String[] temp=message.split(MyTools.SPLIT2);
String userName=temp[0];//用户名
int userState=Integer.parseInt(temp[1]);
String signature=temp[2];//个性签名
String headImage=temp[3];//头像
if(main!=null)
{
main.lbl用户名.setText(userName);
main.comboBox状态.setSelectedIndex(userState);
main.lbl个性签名.setText(signature);
main.lbl头像.setIcon(MyTools.getIcon("../img/headImage/middle/"+headImage+"_64.jpg"));
}
}
public void doGetFriendInfo(String message)
{
JOptionPane.showMessageDialog(null, message);
}
public void doFriendList(String message)
{
System.out.println("客户端已接收到好友列表!");
System.out.println(message);
String[] groupNames=message.split(MyTools.SPLIT1)[0].split(MyTools.SPLIT2);
ArrayList<String[]> friendNames=new ArrayList<String[]>();
for(int i=0;i<groupNames.length;i++)
{
String temp=message.split(MyTools.SPLIT1)[i+1];
if(!temp.equals("无") && !"".equals(temp))
friendNames.add(temp.split(MyTools.SPLIT2));
else
friendNames.add(new String[]{});
}
main.initjTree(groupNames, friendNames);
}
public void doQunChat(String message)
{
if(main.qunChat!=null)
main.qunChat.receiveMessage(message);
else
{
String[] temp=message.split(MyTools.SPLIT1);
new PublicMessageFrame("MyQQ官方聊天室未读消息", temp[0]+"说("+temp[1]+"):\n"+temp[2]);
}
}
/**
* 处理聊天室公告信息
* @param message
*/
public void doPublicMessage(String message)
{
if(main.qunChat!=null)
main.qunChat.showPublicMessage(message);
else
new PublicMessageFrame("MyQQ聊天室公告", message);
}
/**
* 处理弹窗公告信息
*/
public void doShowWindow(String message)
{
new PublicMessageFrame("MyQQ系统公告", message);
try
{
sun.audio.AudioPlayer.player.start(new sun.audio.AudioStream(new FileInputStream(new File("system.wav"))));
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 处理未读消息
* @param message
*/
public void doUnreadMessage(String message)
{
//String[] temp=message.split(MyTools.SPLIT1);
new PublicMessageFrame("您有未读离线消息", message);
MyTools.playMsgSound();
}
}
================================================
FILE: src/client/socket/S_TCP.java
================================================
package client.socket;
import java.applet.Applet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.xml.transform.Templates;
import client.common.MyTextPane;
import client.control.Chat;
import client.control.Main;
import client.control.RecieveThread;
import client.frame.PublicMessageFrame;
import client.frame.SendFileFrame;
import com.MyTools;
import com.MyTools.Flag;
import com.socket.TCP;
import com.socket.TCPServer;
public class S_TCP extends TCPServer
{
ArrayList<Chat> chats=new ArrayList<Chat>();//存放所有的打开的聊天窗体集合
Main main=null;//传过来的主窗体
public S_TCP(int serverPort,Main main)
{
super(serverPort);
this.main=main;
}
/**
* 处理客户端发来的各种信息
* @param flag 信息标志
* @param message 消息内容
*/
@Override
public void dealWithMessage(Flag flag,String message,TCP tcp)
{
switch (flag)
{
case START_CHAT:doStartChat(message,tcp);break;
case MESSAGE:showMessage(message,tcp);break;
case SENDFILE:doSendFile(message,tcp);break;
case SENDIMG: dogetImg(message ,tcp);break;
case FACE:doFace(message,tcp);break;//如果是表情
default:break;
}
}
/**
* 接收图片
* @param message
* @param tcp
*/
private void dogetImg(String message,TCP tcp)
{
Chat currentChatWindoew =
null;
for(Chat chat:chats)
{
if(chat.friendName.equals(tcp.getClientName()))
currentChatWindoew = chat;
}
tcp.getImg(currentChatWindoew ,message);
}
/**
* 处理客户端退出的相关事件
* @param tcp TCP连接
*/
@Override
public void dealWithExit(TCP tcp)
{
}
/**
* 服务端启动后要做的事情,把这部分单独提取出来的目的是为了方便子类继承时重写
*/
@Override
public void afterServerStart()
{
}
public void doStartChat(String message,TCP tcp)
{
tcp.setClientName(message);//设置对方的名字
if(!message.equals(main.lbl用户名.getText()))
{
Chat chat=new Chat(tcp,tcp.getClientName(),main.lbl用户名.getText());
chat.setTitle("与" + tcp.getClientName()+"("+tcp.getClientIP()+")聊天中");// 设置窗体标题
chats.add(chat);
}
else
{
JOptionPane.showMessageDialog(null, "您正在与自己聊天,MyQQ将只会打开一个聊天框!");
}
}
public void showMessage(String message,TCP tcp)
{
for(Chat chat:chats)
{
if(chat.friendName.equals(tcp.getClientName()))
{
if(!chat.isVisible())
{
new PublicMessageFrame(tcp.getClientName()+"给您发来消息",message,chat);
//对方未打开聊天窗体时就播放声音
MyTools.playMsgSound();
}
chat.setReceivePaneText(false, message);
}
}
}
/**
* 处理接收文件的相关事件
*/
public void doSendFile(String message,TCP tcp)
{
for(Chat chat:chats)
{
if(chat.friendName.equals(tcp.getClientName()))
{
chat.friendGetFilePort=Integer.parseInt(message);
System.out.println("已成功获取好友的接收文件端口:"+message);
}
}
}
/**
* 处理表情
* @param message
* @param tcp
*/
public void doFace(String message,TCP tcp)
{
for(Chat chat:chats)
{
if(chat.friendName.equals(tcp.getClientName()))
{
new MyTextPane(chat.jTextPane接收框).addIcon(MyTools.getFaceByIdx(Integer.parseInt(message)), chat.friendName);
}
}
}
}
================================================
FILE: src/client/socket/UDPChat.java
================================================
package client.socket;
import client.control.Chat;
import com.socket.UDP;
public class UDPChat extends UDP
{
Chat chat = null;// 声明一个聊天的类
public UDPChat(String friendIP, Chat parent)
{
super(friendIP);
this.chat = parent;
newThreadGetMessage();
}
/**
* 开辟新线程后台获取消息
*/
public void newThreadGetMessage()
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
while (true)
{
String message = getMessage();// 调用父类UDP的获取消息方法
chat.setReceivePaneText(false, message);// 将接收的消息显示在聊天窗体中的聊天框中
try
{
Thread.sleep(30);// 线程休息100毫秒
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
new Thread(runnable).start();
}
}
================================================
FILE: src/com/MyTools.java
================================================
package com;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.UIManager;
import client.control.Main;
/**
* @author
* 一些经常调用的方法和枚举,都集中放在这里
*/
public class MyTools
{
//下面三句话定义一些标志,示例如下:
//login#马化腾;1234567
//friends_info#我的好友,柳夏南,王林,吴志强;陌生人,胡锦涛,陈水扁
public static final String FLAGEND = "#";//定义最当头标志结束的字符
public static final String SPLIT1 = ";";//定义一级分割字符
public static final String SPLIT2 = ",";//定义二级分割字符
public static final String SPLIT3 = "&";//定义三级分割字符
public static final int QQServerPort = 6776; // QQ服务器端口号
public static final String QQServerIP = "127.0.0.1"; // 服务器IP地址
// 数据库地址和密码
public static final String JDBC_URL = "jdbc:mysql://127.0.0.1:3306/myqq?useUnicode=true&characterEncoding=utf-8";
public static final String JDBC_USER = "root";
public static final String JDBC_PWD = "root";
// public static final String JDBC_URL = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
// public static final String JDBC_USER = "test";
// public static final String JDBC_PWD = "test";
/**
* @author LXA
*定义一个标志的枚举
*/
public enum Flag
{
LOGIN, //“登录”的标志
SUCCESS, //“成功”的标志
FAILED, //“失败”的标志
USERINFO, //“用户信息、好友列表”的标志
FRIENDS_LIST, //好友列表
PORT, //端口号的标志
START_CHAT, //聊天的标志
MESSAGE, //聊天内容的标志
GET_FRIEND_INFO, //获取好友资料的标志
REGISTER, //注册
SENDFILE, //发送文件的标志
GETFILE_OK,
QUN_CHAT, //群聊
PUBLIC_MESSAGE, //公告
SHOW_WINDOW, //弹窗
UNDERLINE_MESSAGE,//离线消息
SENDIMG,//发送图片
FACE//表情
};
/**
* 将窗体居中显示
* @param frame 需要居中显示的窗体
*/
public static void setWindowsMiddleShow(JFrame frame)
{
Dimension screenSize= Toolkit.getDefaultToolkit().getScreenSize();
frame.setBounds((screenSize.width-frame.getWidth())/2, (screenSize.height-frame.getHeight())/2, frame.getWidth(), frame.getHeight());
}
/**
* 将窗体居中显示
* @param frame 需要居中显示的窗体
* @param width 窗体的宽度
* @param height 窗体的高度
*/
public static void setWindowsMiddleShow(JFrame frame,int width,int height)
{
Dimension screenSize= Toolkit.getDefaultToolkit().getScreenSize();
frame.setBounds((screenSize.width-width)/2, (screenSize.height-height)/2, width, height);
}
/**
* 更换皮肤
*/
public static void changeSkin()
{
try
{
//UIManager.put("nimbusBase", Color.red);
//UIManager.put("nimbusBlueGrey", Color.red);//按钮的颜色
UIManager.put("control", new Color(215, 255, 255));//控件背景色
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 根据文件路径获取图片
* @param path 路径
* @return 返回获取的图片
*/
public static ImageIcon getIcon(String path)
{
try
{
//System.out.println(Main.class.getResource(path));
ImageIcon icon=new ImageIcon(ImageIO.read(Main.class.getResource(path)));
return icon;
}
catch (IOException e)
{
System.out.println("图片:"+path+"不存在!");
return null;
}
}
/**
* 将字符串转成Flag类型的枚举
* @param str 需要转的字符串
* @return 返回转换后的Flag枚举
*/
public static Flag stringToFlagEnum(String str)
{
return Enum.valueOf(Flag.class, str);
}
public static String getFaceByIdx(int idx)
{
String fileName="";
if(idx<10)
{
fileName= "../img/face/f00"+idx+".png";//修改图片路径
}
else
{
fileName= "../img/face/f0"+idx+".png";
}
return fileName;
}
/**
* 默认会报如下错误:
* 访问限制:由于对必需的库 D:\GreenSoft\Java\jdk1.6.0_10\jre\lib\rt.jar 具有一定限制,因此无法访问类型 AudioStream
* 需要作如下修改:右键项目-->属性-->Java编译器-->错误/警告-->勾选“启用特定于项目的设置”-->建议不要使用和限制使用的API-->将“禁止的引用”改为警告
*/
public static void playMsgSound()
{
try
{
sun.audio.AudioPlayer.player.start(new sun.audio.AudioStream(new FileInputStream(new File("msg.wav"))));
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void playSystemSound()
{
try
{
sun.audio.AudioPlayer.player.start(new sun.audio.AudioStream(new FileInputStream(new File("system.wav"))));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
================================================
FILE: src/com/socket/TCP.java
================================================
package com.socket;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import client.common.MyTextPane;
import client.control.Chat;
import com.MyTools;
import com.MyTools.Flag;
public class TCP
{
private Socket socket = null;
private String clientName="";//用户名
private int clientServerPort=0;//客户端端口号
private int userState=0;//0表示在线
/**
* 客户端TCP初始化
* @param serverIP 服务端IP地址
* @param serverPort 服务端端口号
* @throws IOException
* @throws UnknownHostException
*/
public TCP(String serverIP, int serverPort) throws Exception
{
socket = new Socket(serverIP, serverPort);
System.out.println("客户端TCP成功启动!");
getMessageNewThread();//对于客户端的TCP,给它启动一个新线程不停的接收消息
}
/**
* TCP的另一种构造方法
* @param server 传过来的Server端TCP连接
*/
public TCP(ServerSocket server)
{
try
{
socket = server.accept();
System.out.println("新增一台客户端与服务端连接!");
}
catch (Exception e)
{
//e.printStackTrace();
}
}
/**
* 关闭Socket连接
*/
public void closeSocket()
{
try
{
if(socket!=null)
socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* 开辟新线程后台接收消息并处理
* @param tcp 传过来的TCP连接
*/
public void getMessageNewThread()
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
boolean exit=false;
while(!exit)
{
try
{
//将获取的消息按#分割,msg[0]的表示标志,msg[1]表示内容
String[] temp=getMessage().split(MyTools.FLAGEND);
String flagHead=temp[0];//获取消息的标志
String message=temp[1];//获取消息的真实内容
Flag flag=MyTools.stringToFlagEnum(flagHead);//获取标志
dealWithMessage(flag,message);
}
catch (Exception e)
{
dealWithExit();
exit=true;
}
}
}
};
new Thread(runnable).start();
}
public void dealWithMessage(Flag flag,String message)
{
}
public void dealWithExit()
{
}
/**
* 发送消息
* @param text
* 要发送的文本
*/
public void sendMessage(String text)
{
try
{
socket.getOutputStream().write(text.getBytes());
System.out.println("TCP成功发送:" + text);
Thread.sleep(100);//每发送完一个消息线程休息一下,防止连续发送消息重叠在一起
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 获取消息
*
* @return 获取的文本
*/
public String getMessage() throws Exception
{
byte[] b = new byte[1024];
int len = socket.getInputStream().read(b);
String str = new String(b, 0, len);
System.out.println("TCP接收到:" + str);
return str;
}
public void sendFile()
{
}
/**
* @param imgPath
* 根据图片路径发送图片
*
*/
public void sendImg(String imgPath)
{
try
{
File imgFile = new File(imgPath);
FileInputStream imgFileIn = new FileInputStream(imgFile);
// 获取文件名
String imgName = imgFile.getName();
byte[] buff = new byte[1024];
int len = 0;
// 首先发送文件名
sendMessage(Flag.SENDIMG+MyTools.FLAGEND+imgName);
OutputStream out = socket.getOutputStream();
// out.write(imgName.getBytes());
// 开始发送图片
System.out.println("开始发送图片……");
if(socket.isClosed())
System.out.println("已关闭");
else {
System.out.println("未关闭");
}
while ((len = imgFileIn.read(buff)) != -1)
{
System.out.println("111");
out.write(buff, 0, len);
System.out.println("222");
}
out.write("#文件发送完毕#".getBytes());
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("图片已发送完成");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* 得到图片
*/
public void getImg(Chat chat ,String imgName)
{
File imgFile = null;
try
{
InputStream in = socket.getInputStream();
byte[] buff = new byte[1024];
int len = 0;
// 存放接收文件对象
imgFile = new File("./" + System.currentTimeMillis() + imgName);
FileOutputStream imgOut = new FileOutputStream(imgFile);
System.out.println("12342");
len = 1024;//in.read(buff,0,buff.length);
//imgOut.write(buff, 0, len);
while (len ==1024)
{
System.out.println("len="+len);
System.out.println("图片正在接收....");
len = in.read(buff,0,buff.length);
String str=new String(buff,0,len);
if(str.equals("#文件发送完毕#"))
break;
imgOut.write(buff, 0, len);
}
System.out.println("图片接收完成");
in.close();
imgOut.close();
new MyTextPane(chat.jTextPane接收框).addIcon(ImageIO
.read(new FileInputStream(imgFile)), chat.friendName);
//chat.jTextPane接收框.insertIcon(new ImageIcon()));
System.out.println("图片插入完成");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取客户端的IP地址
* @return
*/
public String getClientIP()
{
return socket.getInetAddress().getHostAddress().replaceAll("/", "");
}
/**
* 获取本机IP地址
* @return 返回字符串形式的IP地址
*/
public static String getLocalHostIP()
{
try
{
return InetAddress.getLocalHost().getHostAddress().replaceAll("/", "");
}
catch (UnknownHostException e)
{
return null;
}
}
/**
* 获取客户端的用户名
* @return
*/
public String getClientName()
{
return clientName;
}
/**
* 设置客户端的用户名
* @param name
*/
public void setClientName(String name)
{
this.clientName=name;
}
/**
* 获取客户端的TCP服务端端口号
* @return
*/
public int getClientServerPort()
{
return clientServerPort;
}
/**
* 设置客户端的TCP服务端端口号
* @param clientPort
*/
public void setClientServerPort(int clientServerPort)
{
this.clientServerPort=clientServerPort;
}
/**
* 获取服务端的端口号
*/
public int getServerPort()
{
return socket.getLocalPort();//返回自己的端口,如5000
}
public int getClientPort()
{
return socket.getPort();//返回与别人建立连接的端口,如65544
}
/**
* 设置当前登录用户状态
* @param userState
*/
public void setUserState(int userState)
{
this.userState=userState;
}
/**
* 获取当前登录用户状态
* @return
*/
public int getUserState()
{
return userState;
}
}
================================================
FILE: src/com/socket/TCPServer.java
================================================
package com.socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import com.MyTools;
import com.MyTools.Flag;
import com.socket.TCP;
public class TCPServer
{
public ServerSocket server = null;// 服务端
public ArrayList<TCP> tcpSockets = new ArrayList<TCP>();// 存放与客户端的TCPSocket连接
private int serverPort = 0;//服务端的端口
public boolean isStart = false;// 是否启动了服务端
/**
* 服务端TCP初始化
* @param server 服务端
*/
public TCPServer(int serverPort)
{
this.serverPort=serverPort;
isStart = true;
if(startServerTCP())//启动TCP服务端
{
afterServerStart(); //服务端启动后要做的事情
getConnectionNewThread();//开辟新线程不断的接受连接
}
}
/**
* 关闭服务器
*/
public void closeServer()
{
isStart=false;
try
{
server.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* 启动TCP服务端
*/
public boolean startServerTCP()
{
if(serverPort==MyTools.QQServerPort)//如果启动的是QQ服务器
{
try
{
server=new ServerSocket(serverPort);
return true;
}
catch (IOException e)
{
System.out.println("启动QQ服务器失败!端口"+serverPort+"已被占用,请检查是否已开启了一个QQ服务器!");
return false;
}
}
else//如果启动的是普通TCP服务端
{
while(true)
{
try
{
server = new ServerSocket(serverPort);
break;
}
catch (IOException e)
{
serverPort++;
}
}
return true;
}
}
/**
* 开辟新线程不断的接受连接
*/
public void getConnectionNewThread()
{
Runnable runnable=new Runnable()
{
@Override
public void run()
{
while (isStart)
{
TCP tcp = new TCP(server);
tcpSockets.add(tcp);
getMessageNewThread(tcp);
}
}
};
new Thread(runnable).start();
}
/**
* 开辟新线程后台接收消息并处理
* @param tcp 传过来的TCP连接
*/
public void getMessageNewThread(final TCP tcp)
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
boolean exit=false;
while(!exit)
{
try
{
//将获取的消息按#分割,msg[0]的表示标志,msg[1]表示内容
String[] temp=tcp.getMessage().split(MyTools.FLAGEND);
String flagHead=temp[0];//获取消息的标志
String message=temp[1];//获取消息的真实内容
Flag flag=MyTools.stringToFlagEnum(flagHead);//获取标志
dealWithMessage(flag,message,tcp);
}
catch (Exception e)
{
//e.printStackTrace();
if(tcpSockets.remove(tcp))//从ArrayList中移除已退出的用户
{
dealWithExit(tcp);
}
exit=true;
}
}
}
};
new Thread(runnable).start();
}
/**
* 处理客户端发来的各种信息
* @param flag 信息标志
* @param message 消息内容
* @param tcp TCP连接
*/
public void dealWithMessage(Flag flag,String message,TCP tcp)
{
}
/**
* 处理客户端退出的相关事件
* @param tcp TCP连接
*/
public void dealWithExit(TCP tcp)
{
}
/**
* 服务端启动后要做的事情,把这部分单独提取出来的目的是为了方便子类继承时重写
*/
public void afterServerStart()
{
System.out.println("服务端TCP已启动!端口号:"+serverPort);
}
public int getServerPort()
{
return serverPort;
}
}
================================================
FILE: src/com/socket/UDP.java
================================================
package com.socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.BreakIterator;
public class UDP
{
public DatagramSocket socket = null;// 通过UDP建立的Socket
private int myPort = 6000;// 我的端口,从6000开始查找可用的端口号
public InetAddress friendIP = null;// 好友的IP地址
public int friendPort = 0;// 好友的端口
public UDP(String friendIP)
{
getMyUsefulPort();
try
{
this.friendIP = InetAddress.getByName(friendIP);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 设置好友的端口号
* @param friendPort
*/
public void setFriendPort(int friendPort)
{
this.friendPort=friendPort;
}
/**
* 获取我的端口号,只有当UDP类被实例化后才能调用此方法,
* 否则得到的端口号可能不是最终有效的端口号
* @return
*/
public int getMyPort()
{
return this.myPort;
}
/**
* 获取可用的端口号
*/
public void getMyUsefulPort()
{
while(true)
{
try
{
// 实例化一个DatagramSocket
socket = new DatagramSocket(myPort);
break;
}
catch (SocketException e)
{
myPort++;
}
}
}
/*
* 给好友发送消息
*/
public void sendMessage(String text)
{
byte[] data = text.getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, friendIP,
friendPort);
try
{
socket.send(packet);// 开始发送消息
System.out.println("使用UDP成功发送:"+text);
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* 接收消息
*/
public String getMessage()
{
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, buf.length);
try
{
socket.receive(dp);
String message = new String(dp.getData(), 0, dp.getLength());
System.out.println("使用UDP成功接收到:"+message);
return message;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* 开辟新线程后台获取消息,这个方法姑且丢置在这里,暂时不会用到
*/
public void newThreadGetMessage()
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
while (true)
{
getMessage();// 调用UDP的获取消息方法
try
{
Thread.sleep(100);// 线程休息100毫秒
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
new Thread(runnable).start();
}
}
================================================
FILE: src/log4j-1.2.dtd
================================================
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Authors: Chris Taylor, Ceki Gulcu. -->
<!-- Version: 1.2 -->
<!-- A configuration element consists of optional renderer
elements,appender elements, categories and an optional root
element. -->
<!ELEMENT log4j:configuration (renderer*, appender*,plugin*, (category|logger)*,root?,
(categoryFactory|loggerFactory)?)>
<!-- The "threshold" attribute takes a level value below which -->
<!-- all logging statements are disabled. -->
<!-- Setting the "debug" enable the printing of internal log4j logging -->
<!-- statements. -->
<!-- By default, debug attribute is "null", meaning that we not do touch -->
<!-- internal log4j logging settings. The "null" value for the threshold -->
<!-- attribute can be misleading. The threshold field of a repository -->
<!-- cannot be set to null. The "null" value for the threshold attribute -->
<!-- simply means don't touch the threshold field, the threshold field -->
<!-- keeps its old value. -->
<!ATTLIST log4j:configuration
xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/"
threshold (all|trace|debug|info|warn|error|fatal|off|null) "null"
debug (true|false|null) "null"
reset (true|false) "false"
>
<!-- renderer elements allow the user to customize the conversion of -->
<!-- message objects to String. -->
<!ELEMENT renderer EMPTY>
<!ATTLIST renderer
renderedClass CDATA #REQUIRED
renderingClass CDATA #REQUIRED
>
<!-- Appenders must have a name and a class. -->
<!-- Appenders may contain an error handler, a layout, optional parameters -->
<!-- and filters. They may also reference (or include) other appenders. -->
<!ELEMENT appender (errorHandler?, param*,
rollingPolicy?, triggeringPolicy?, connectionSource?,
layout?, filter*, appender-ref*)>
<!ATTLIST appender
name CDATA #REQUIRED
class CDATA #REQUIRED
>
<!ELEMENT layout (param*)>
<!ATTLIST layout
class CDATA #REQUIRED
>
<!ELEMENT filter (param*)>
<!ATTLIST filter
class CDATA #REQUIRED
>
<!-- ErrorHandlers can be of any class. They can admit any number of -->
<!-- parameters. -->
<!ELEMENT errorHandler (param*, root-ref?, logger-ref*, appender-ref?)>
<!ATTLIST errorHandler
class CDATA #REQUIRED
>
<!ELEMENT root-ref EMPTY>
<!ELEMENT logger-ref EMPTY>
<!ATTLIST logger-ref
ref CDATA #REQUIRED
>
<!ELEMENT param EMPTY>
<!ATTLIST param
name CDATA #REQUIRED
value CDATA #REQUIRED
>
<!-- The priority class is org.apache.log4j.Level by default -->
<!ELEMENT priority (param*)>
<!ATTLIST priority
class CDATA #IMPLIED
value CDATA #REQUIRED
>
<!-- The level class is org.apache.log4j.Level by default -->
<!ELEMENT level (param*)>
<!ATTLIST level
class CDATA #IMPLIED
value CDATA #REQUIRED
>
<!-- If no level element is specified, then the configurator MUST not -->
<!-- touch the level of the named category. -->
<!ELEMENT category (param*,(priority|level)?,appender-ref*)>
<!ATTLIST category
class CDATA #IMPLIED
name CDATA #REQUIRED
additivity (true|false) "true"
>
<!-- If no level element is specified, then the configurator MUST not -->
<!-- touch the level of the named logger. -->
<!ELEMENT logger (level?,appender-ref*)>
<!ATTLIST logger
name CDATA #REQUIRED
additivity (true|false) "true"
>
<!ELEMENT categoryFactory (param*)>
<!ATTLIST categoryFactory
class CDATA #REQUIRED>
<!ELEMENT loggerFactory (param*)>
<!ATTLIST loggerFactory
class CDATA #REQUIRED>
<!ELEMENT appender-ref EMPTY>
<!ATTLIST appender-ref
ref CDATA #REQUIRED
>
<!-- plugins must have a name and class and can have optional parameters -->
<!ELEMENT plugin (param*, connectionSource?)>
<!ATTLIST plugin
name CDATA #REQUIRED
class CDATA #REQUIRED
>
<!ELEMENT connectionSource (dataSource?, param*)>
<!ATTLIST connectionSource
class CDATA #REQUIRED
>
<!ELEMENT dataSource (param*)>
<!ATTLIST dataSource
class CDATA #REQUIRED
>
<!ELEMENT triggeringPolicy ((param|filter)*)>
<!ATTLIST triggeringPolicy
name CDATA #IMPLIED
class CDATA #REQUIRED
>
<!ELEMENT rollingPolicy (param*)>
<!ATTLIST rollingPolicy
name CDATA #IMPLIED
class CDATA #REQUIRED
>
<!-- If no priority element is specified, then the configurator MUST not -->
<!-- touch the priority of root. -->
<!-- The root category always exists and cannot be subclassed. -->
<!ELEMENT root (param*, (priority|level)?, appender-ref*)>
<!-- ==================================================================== -->
<!-- A logging event -->
<!-- ==================================================================== -->
<!ELEMENT log4j:eventSet (log4j:event*)>
<!ATTLIST log4j:eventSet
xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/"
version (1.1|1.2) "1.2"
includesLocationInfo (true|false) "true"
>
<!ELEMENT log4j:event (log4j:message, log4j:NDC?, log4j:throwable?,
log4j:locationInfo?, log4j:properties?) >
<!-- The timestamp format is application dependent. -->
<!ATTLIST log4j:event
logger CDATA #REQUIRED
level CDATA #REQUIRED
thread CDATA #REQUIRED
timestamp CDATA #REQUIRED
time CDATA #IMPLIED
>
<!ELEMENT log4j:message (#PCDATA)>
<!ELEMENT log4j:NDC (#PCDATA)>
<!ELEMENT log4j:throwable (#PCDATA)>
<!ELEMENT log4j:locationInfo EMPTY>
<!ATTLIST log4j:locationInfo
class CDATA #REQUIRED
method CDATA #REQUIRED
file CDATA #REQUIRED
line CDATA #REQUIRED
>
<!ELEMENT log4j:properties (log4j:data*)>
<!ELEMENT log4j:data EMPTY>
<!ATTLIST log4j:data
name CDATA #REQUIRED
value CDATA #REQUIRED
>
================================================
FILE: src/log4j.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j-1.2.dtd">
<log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- 设置根日志,这个决定不同级别的日志具体输出到哪些地方 -->
<root>
<priority value="debug" />
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
<!-- 控制台配置 -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[LXA][%p] %d{yyyy年MM月dd日 HH:mm:ss} %m%n" />
</layout>
</appender>
<!-- 文件配置 -->
<appender name="file" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="${catalina.home}/logs/lxa.log"/>
<param name="DatePattern" value="'-'yyyy-MM-dd'.txt'"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[LXA][%p] %d{yyyy年MM月dd日 HH:mm:ss:SSS} %l:%n%m%n%n"/>
</layout>
</appender>
<!-- 对特殊类进行级别的特殊设置 -->
<logger name="com.lxa">
<level value="debug" />
</logger>
<!--
格式化日志信息:
%d{yyyy-MM-dd} 时间
%p 模式,如INFO或者DEBUG
%c 类的全名
%L 行数
%l 具体调用的方法名(包括类全名)
%m 输出的信息
%n 换行
-->
</log4j:configuration>
================================================
FILE: src/server/QQServer.java
================================================
package server;
import java.sql.Date;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import server.dao.MsgDao;
import server.dao.UserDao;
import server.entity.Msg;
import server.entity.Users;
import com.MyTools;
import com.MyTools.Flag;
import com.socket.TCP;
import com.socket.TCPServer;
/**
* @author LXA 服务端
*/
public class QQServer extends TCPServer
{
UserDao userDao;
MsgDao msgDao;
public QQServer(int serverPort)
{
super(serverPort);
userDao=new UserDao();
msgDao=new MsgDao();
}
/**
* 主函数
* @param args
*/
// public static void main(String[] args)
// {
// new QQServer(MyTools.QQServerPort);
// }
/**
* 处理客户端发来的各种信息
* @param flag 信息标志
* @param message 消息内容
* @param tcp TCP连接
*/
@Override
public void dealWithMessage(Flag flag, String message,TCP tcp)
{
switch(flag)
{
case LOGIN:doLogin(message,tcp);break;//如果是登录
case GET_FRIEND_INFO:doGetFriendInfo(message,tcp);break;//处理用户发来的请求好友资料的事件
case REGISTER:doRegister(message,tcp);break;
case QUN_CHAT:doQunChat(message,tcp);break;
case UNDERLINE_MESSAGE:doUnderlineMessage(message,tcp);break;//处理用户发来的离线消息
default:break;
}
}
/**
* 处理客户端退出的相关事件
* @param tcp TCP连接
*/
@Override
public void dealWithExit(TCP tcp)
{
refreshAllUserFriendList();
userDao.updateUserState(tcp.getClientName(), -1+"");//将用户的状态更新到数据库中去
userDao.setLastExit(tcp.getClientName());
System.out.println("用户"+tcp.getClientName()+"已退出!");
showOnlineNumber();
}
/*
* 服务端启动后要做的事情
*/
@Override
public void afterServerStart()
{
System.out.println("QQ服务器已启动!");
showOnlineNumber();
}
/**
* 处理客户端登录
* @param message
*/
public void doLogin(String message,TCP tcp)
{
System.out.println("客户端"+tcp.getClientIP()+"尝试登录……");
String[] temp=message.split(MyTools.SPLIT1);
String name=temp[0];//用户名
String password=temp[1];//用户密码
int port=Integer.parseInt(temp[2]);//用户端口号
int userState=Integer.parseInt(temp[3]);//用户状态
System.out.println("nihao");
if(checkNameAndPwd(name, password))//如果用户名和密码都正确
{
if(checkIsLoginAgain(name))//如果重复登录
tcp.sendMessage(Flag.LOGIN+MyTools.FLAGEND+Flag.FAILED+MyTools.SPLIT1+"您不能重复登录!");
else
{
tcp.setClientName(name);//设置登录用户的名字到TCP中保存
tcp.setClientServerPort(port);//保存当前登录用户的端口
tcp.setUserState(userState);//保存当前登录用户的状态
userDao.updateUserState(name, userState+"");//将用户的状态保存到数据库中去
userDao.setLastLogin(name);
userDao.setIP(tcp.getClientIP(), name);//将用户的IP存往数据库
tcp.sendMessage(Flag.LOGIN+MyTools.FLAGEND+Flag.SUCCESS+MyTools.SPLIT1+getCurrentUserInfo(tcp));//发送一个消息给用户提示登录成功
try
{
Thread.sleep(50);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
refreshAllUserFriendList();//刷新所有用户的好友列表,但不包括当前登录用户
try
{
Thread.sleep(50);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
sendUnreadMessage(tcp);//发送用户未读消息
showOnlineNumber();//显示当前在线人数
}
}
else//如果登录失败
{
tcp.sendMessage(Flag.LOGIN+MyTools.FLAGEND+Flag.FAILED+MyTools.SPLIT1+"用户名或密码错误!");
}
}
/**
* 处理用户发来的请求好友资料的事件
* @param message
* @param tcp
*/
public void doGetFriendInfo(String message,TCP tcp)
{
Users users = userDao.queryByName(tcp.getClientName());
StringBuffer sb=new StringBuffer();
sb.append("用户ID:"+users.getId()+"\n");
sb.append("用户名:"+users.getName()+"\n");
sb.append("性别:"+users.getGender()+"\n");
sb.append("电子邮件:"+users.getEmail()+"\n");
sb.append("最后一次登录:"+users.getLastLogin()+"\n");
sb.append("最后一次退出:"+users.getLastExit()+"\n");
sb.append("个性签名:"+users.getSignature()+"\n");
sb.append("生日:"+users.getBirthday()+"\n");
String userInfo=new String(sb);
tcp.sendMessage(Flag.GET_FRIEND_INFO+MyTools.FLAGEND+userInfo);
}
/**
* 处理用户发来的注册请求
* @param message
* @param tcp
*/
public void doRegister(String message,TCP tcp)
{
String[] temp=message.split(MyTools.SPLIT1);
String name=temp[0];//姓名
String password=temp[1];//密码
String sex=temp[2];//性别
String email=temp[3];//电子邮件
Date birthday;//生日
String repost="恭喜你,注册成功!";//给用户的回复
try
{
System.out.println("生日:"+temp[4]);
birthday=Date.valueOf(temp[4]);
System.out.println(birthday);
}
catch (Exception e)
{
birthday=Date.valueOf("1992-07-28");
repost+="\n但是您的生日日期格式不正确,系统已给您设置成默认的生日:1992-07-28!";
}
String signature=temp[5];//个性签名
String headImageIdx=temp[6];//头像索引
Users users=new Users(name, password, sex, email, signature, headImageIdx, birthday);
if(userDao.checkUserIsExit(name))
tcp.sendMessage(Flag.REGISTER+MyTools.FLAGEND+Flag.FAILED+MyTools.SPLIT1+"用户名已存在!");
else
{
try
{
userDao.add(users);
tcp.sendMessage(Flag.REGISTER+MyTools.FLAGEND+Flag.SUCCESS+MyTools.SPLIT1+repost);
}
catch (SQLException e)
{
e.printStackTrace();
tcp.sendMessage(Flag.REGISTER+MyTools.FLAGEND+Flag.FAILED+MyTools.SPLIT1+"由于某些原因,注册失败!");
}
}
}
/**
* 检查登录用户的用户名和密码是否正确
* @param name
* @param password
* @return
*/
public boolean checkNameAndPwd(String name,String password)
{
boolean success=false;
if(userDao.checkNameAndPwd(name, password))
success=true;
return success;
}
/**
* 检查用户是否重复登录
* @param name 用户名
* @return 返回的真假值
*/
public boolean checkIsLoginAgain(String name)
{
boolean res=false;
for(TCP tcp:tcpSockets)
if(tcp.getClientName().equals(name))
{
res=true;
break;
}
return res;
}
/**
* 初始化客户端信息
* @param tcp
*/
public void initClientInfo(TCP tcp)
{
tcp.sendMessage(Flag.USERINFO+MyTools.FLAGEND+getCurrentUserInfo(tcp));
}
/**
* 刷新所有在线用户的好友列表
*/
public void refreshAllUserFriendList()
{
for(TCP tcp:tcpSockets)
tcp.sendMessage(Flag.FRIENDS_LIST+MyTools.FLAGEND+getAllUsersInfo());
}
/**
* 获取当前用户的信息
* @param t
* @return
*/
public String getCurrentUserInfo(TCP tcp)
{
//示例:用户名;状态;个性签名;头像
StringBuffer sb=new StringBuffer();
String userName=tcp.getClientName();
Users users=userDao.queryByName(userName);//从数据库中查询用户信息
sb.append(userName+MyTools.SPLIT2//用户名
+tcp.getUserState()+MyTools.SPLIT2//状态
+users.getSignature()+MyTools.SPLIT2//签名
+users.getHeadImg());//头像
String userInfo=new String(sb);//返回当前登录用户自己的信息
return userInfo;
}
/**
* 将所有用户的信息转换成字符串
* @return
*/
public String getAllUsersInfo()
{
//示例:刘显安,192.168.1.1,8888;吴志强,192.168.1.2,6666
StringBuffer sb=new StringBuffer();
sb.append("所有在线用户"+MyTools.SPLIT2+"所有不在线用户"+MyTools.SPLIT2+"我的好友"+MyTools.SPLIT1);
for(TCP tcp:tcpSockets)
{
if(tcp.getUserState()!=4)//因为4表示隐身
{
System.out.println("客户端名"+tcp.getClientName());
sb.append(tcp.getClientName()+MyTools.SPLIT3//用户名
+tcp.getClientIP()+MyTools.SPLIT3//IP
+tcp.getClientServerPort()+MyTools.SPLIT3//端口号
+userDao.queryByName(tcp.getClientName()).getHeadImg()+MyTools.SPLIT3//头像
+tcp.getUserState()+MyTools.SPLIT2);//用户状态
}
}
String onlineUser=new String(sb);
onlineUser=onlineUser.substring(0,onlineUser.length()-1);//去掉最后一个逗号
onlineUser+=MyTools.SPLIT1;//加上一个分号
sb=new StringBuffer();
ArrayList<Users> userList=userDao.queryAll();
for(Users users:userList)
{
if(users.getState().equals("-1")||users.getState().equals("4")||users.getState()==null)
{
sb.append(users.getName()+MyTools.SPLIT3
+"下线或隐身"+MyTools.SPLIT3
+"0"+MyTools.SPLIT3
+users.getHeadImg()+MyTools.SPLIT3
+"-1"+MyTools.SPLIT2);
}
}
String underlineUser=new String(sb);
if(!underlineUser.equals(""))
underlineUser=underlineUser.substring(0,underlineUser.length()-1);//去掉最后一个逗号
underlineUser+=MyTools.SPLIT1;//加上一个分号
String myfriend="无";
return onlineUser+underlineUser+myfriend;
}
/**
* 显示当前在线人数
*/
public void showOnlineNumber()
{
System.out.println("当前总在线人数:"+tcpSockets.size());
}
public void doQunChat(String message,TCP tcp)
{
for(TCP t:tcpSockets)
t.sendMessage(Flag.QUN_CHAT+MyTools.FLAGEND+message);
}
/**
* 处理用户发来的离线消息
* @param message
* @param tcp
*/
public void doUnderlineMessage(String message,TCP tcp)
{
int sendFrom=userDao.queryByName(tcp.getClientName()).getId();
int sendTo=userDao.queryByName(message.split(MyTools.SPLIT1)[0]).getId();
Msg msg=new Msg(message.split(MyTools.SPLIT1)[1],sendFrom,sendTo,"", "");
try
{
msgDao.insertMsg(msg);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
/**
* 给用户发送未读消息
*/
public void sendUnreadMessage(TCP tcp)
{
String userName=tcp.getClientName();
int userID=userDao.queryByName(userName).getId();
ArrayList<Msg> msgs=(ArrayList<Msg>) msgDao.selectMsgBySendTo(userID);
StringBuffer sb=new StringBuffer();
sb.append(Flag.UNDERLINE_MESSAGE+MyTools.FLAGEND);
if(msgs.size()>0)
{
for(Msg msg:msgs)
{
sb.append(userDao.queryById(msg.getSendFrom()).getName()+"("
+msg.getSendTime()+"):\n"
+msg.getMsgContent()+"\n");
}
String unreadMessage=new String(sb);
tcp.sendMessage(unreadMessage);
System.out.println("给用户发送未读离线消息成功!");
msgDao.deleteMsgBySendTO(userID);
System.out.println("删除用户未读消息成功!");
}
}
/**
* 发送聊天室公告
* @param message
*/
public void sendPublicMessage(String message)
{
for(TCP t:tcpSockets)
t.sendMessage(Flag.PUBLIC_MESSAGE+MyTools.FLAGEND+message);
JOptionPane.showMessageDialog(null, "公告发布成功!","恭喜",JOptionPane.INFORMATION_MESSAGE);
}
/**
* 发送弹窗公告
* @param message
*/
public void sendShowWindow(String message)
{
for(TCP t:tcpSockets)
t.sendMessage(Flag.SHOW_WINDOW+MyTools.FLAGEND+message);
JOptionPane.showMessageDialog(null, "弹窗公告发布成功!","恭喜",JOptionPane.INFORMATION_MESSAGE);
}
}
================================================
FILE: src/server/common/JDBC.java
================================================
package server.common;
import java.awt.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import com.MyTools;
public class JDBC
{
public Connection con = null;
public PreparedStatement preSta = null;
public ResultSet result = null;
/**
* 无参的构造方法
*/
public JDBC()
{
getConnection();
}
/**
* 有参的构造方法
* @param url
* @param user 用户名
* @param password
*/
public JDBC(String url,String user,String password)
{
getConnection(url,user,password);
}
/**
* 获取连接
* @param url 连接数据库的URL
* @param user 用户名
* @param password 密码
* @return
*/
private Connection getConnection(String url,String user,String password)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("开始尝试连接数据库!");
con = DriverManager.getConnection(url, user, password);
System.out.println("连接成功!");
}
catch (Exception e)
{
System.out.println("执行数据库操作报错!");
e.printStackTrace();
}
return con;
}
/**
* 使用默认的参数获取数据库的连接
* @return
*/
private Connection getConnection()
{
return getConnection(MyTools.JDBC_URL, MyTools.JDBC_USER, MyTools.JDBC_PWD);
}
/**
* 关闭数据库的连接
*/
public void closeConnection()
{
try
{
if(result!=null)
result.close();
if(preSta!=null)
preSta.close();
if (con != null)
con.close();
System.out.println("数据库连接已关闭!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 执行数据库的更新操作
* @param sql 需要执行的预编译语句
* @param params 预编译语句的参数列表
* @return 受影响的行数
* @throws SQLException
*/
public int update(String sql,String[] params) throws SQLException
{
int count=0;
preSta=con.prepareStatement(sql);
if(params!=null)
{
for(int i=0;i<params.length;i++)
preSta.setString(i+1, params[i]);
}
count=preSta.executeUpdate();
return count;
}
/**
* 执行数据库的查询操作
* @param sql 需要执行的预编译语句
* @param params 预编译语句的参数列表
* @return 返回查询的结果集,类型为ResultSet
* @throws SQLException
*/
public ResultSet query(String sql,String[] params)
{
try
{
preSta=con.prepareStatement(sql);
if(params!=null)
{
for(int i=0;i<params.length;i++)
preSta.setString(i+1, params[i]);
}
result=preSta.executeQuery();
}
catch (SQLException e)
{
e.printStackTrace();
}
return result;
}
/**
* 写入配置文件
* @param url jdbc连接域名
* @param user 用户名
* @param password 密码
*/
public static void writeProperties(String url,String user,String password)
{
Properties pro=new Properties();
FileOutputStream fileOut=null;
try
{
fileOut=new FileOutputStream("Config.ini");
pro.put("url", url);
pro.put("user", user);
pro.put("password", password);
pro.store(fileOut, "My Config");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(fileOut!=null)
fileOut.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* 读取配置文件
* @return 返回list
*/
public static List readProperties()
{
List list=new List();
Properties pro=new Properties();
FileInputStream fileIn=null;
try
{
fileIn=new FileInputStream("Config.ini");
pro.load(fileIn);
list.add(pro.getProperty("url"));
list.add(pro.getProperty("user"));
list.add(pro.getProperty("password"));
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(fileIn!=null)
fileIn.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return list;
}
}
================================================
FILE: src/server/common/Page.java
================================================
package server.common;
public class Page {
private int totalRecords; //总记录数
private int totalPage; //总页数
private int pageSize; //每页显示几条记录
public static int currentPage; //当前页
public int getTotalRecords() {
return totalRecords;
}
public void setTotalRecords(int totalRecords) {
this.totalRecords = totalRecords;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
Page.currentPage = currentPage;
}
}
================================================
FILE: src/server/common/PageService.java
================================================
package server.common;
import java.util.ArrayList;
import java.util.List;
public class PageService {
Page page; //定义一个page的封闭类
List listAll; //把总记录数从页面传过来
public PageService(List listAll) {
this.listAll = listAll;
initPage();
}
/**
* 初始化分页
*
*/
private void initPage() {
page = new Page();
page.setCurrentPage(0); //初始化分页的当前第0页
page.setPageSize(5); //设置每页
page.setTotalRecords(listAll.size()); //获取页面传过来的总记录数
/**
* 计算总页数,第一种: (总记录数+每页显示记录数-1)/每页显示记录数
*
* 第二种
* if(总记录数%每页显示的记录数!=0)
* 总页数=总记录数/每页显示的记录数+1
* else
* 总页数=总记录数/每页显示的记录数
*/
int totalPage = page.getTotalRecords() / page.getPageSize();
if (page.getTotalRecords() % page.getPageSize() != 0) {
totalPage++;
}
page.setTotalPage(totalPage);
}
/**
* 当页面是第一页的时候 ,继续点击上一页出现的情况
* 传一个值 ,如果值 小于等于0,就返回第一页
* 当页面是最后一页的时候 ,继续点击上一页出现的情况
* 如果 这个值大于总页数,就返回最后一页
* 记录每页从哪一条记录开始
* @param target
* @return
*/
public List gotoPage(int target) {
if (target <= 0) {
target = 0;
} else if (target >= page.getTotalPage() - 1) {
target = page.getTotalPage() - 1;
}
page.setCurrentPage(target);
List listPerPage = new ArrayList();
for (int i = target * page.getPageSize(); (i < (target + 1)
* page.getPageSize())
&& (i < page.getTotalRecords()); i++) {
listPerPage.add(listAll.get(i));
}
return listPerPage;
}
/**
* 跳转到首页
* @return
*/
public List gotoFirst(){
return this.gotoPage(0);
}
/**
* 跳转到下一页
* @return
*/
public List gotoNext(){
return this.gotoPage(page.getCurrentPage()+1);
}
/**
* 跳转到上一页,只要当前页-1
* @return
*/
public List gotoPre(){
return this.gotoPage(page.getCurrentPage()-1);
}
/**
* 跳转到最后 一页,获取page的totalPage就是最后一页
* @return
*/
public List gotoLast(){
return this.gotoPage(page.getTotalPage()-1);
}
public int getTotalPage()
{
return page.getTotalPage();
}
public int getCurrentPage()
{
return page.getCurrentPage();
}
public int getTotalRecord()
{
return page.getTotalRecords();
}
public int getPageSize()
{
return page.getPageSize();
}
}
================================================
FILE: src/server/dao/IMsg.java
================================================
package server.dao;
import java.sql.SQLException;
import java.util.List;
import server.entity.Msg;
public interface IMsg
{
public boolean insertMsg(Msg msg)throws SQLException;
public boolean deleteMsg(int msgId)throws SQLException;
public int updateMsg(Msg msg)throws SQLException;
public Msg selectAMsg(int msgId);
public List<Msg> selectMsgs(String sql);
}
================================================
FILE: src/server/dao/IUser.java
================================================
package server.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import server.entity.Users;
/**
* @author Administrator
*用户类数据库操作接口
*/
public interface IUser {
/**
* @param userid
* @return根据用户编号查询单条用户数据
*/
public Users queryById(int usersid) ;
/**
* @return查询所有用户信息
*/
public List<Users> queryAll() ;
/**
* @param user
* @return返回是否添加成功
*/
public boolean add(Users user)throws SQLException;
/**
* @param user
* @return返回是否修改成功
*/
public boolean update(Users user)throws SQLException;
/**
* @param userid
* @return返回是否删除成功
*/
public boolean delete(int usersid)throws SQLException;
/**
* 检测用户名是否已存在
* @param name
* @return
*/
public boolean checkUserIsExit(String name);
/**
* 检测用户名或密码是否正确
* @param name
* @param password
* @return
*/
public boolean checkNameAndPwd(String name,String password);
/**
* 更新用户状态
* @param name
* @param state
* @return
*/
public boolean updateUserState(String name,String state);
/**
* @param userid
* @return根据用户编号查询单条用户数据
*/
public Users queryByName(String name);
}
================================================
FILE: src/server/dao/MsgDao.java
================================================
package server.dao;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.text.DateFormat;
import java.util.List;
import javax.naming.spi.DirStateFactory.Result;
import server.common.JDBC;
import server.entity.Msg;
public class MsgDao implements IMsg
{
JDBC jdbc = new JDBC();
public boolean insertMsg(Msg msg) throws SQLException
{
String sql = "insert into msg(msg_content,msg_sendfrom,msg_sendto,msg_sendtime,msg_remark,msg_type) values (?,?,?,CURRENT_TIMESTAMP,?,?)";
String[] strArr = new String[]{msg.getMsgContent(), String.valueOf(msg.getSendFrom()),
String.valueOf(msg.getSendTo()), msg.getRemark(), msg.getMsgTye(),
};
if(jdbc.update(sql, strArr) > 0)
return true;
return false;
}
@Override
public boolean deleteMsg(int msgId) throws SQLException
{
String sql = "delete from msg where msg_id = ?";
return jdbc.update(sql, new String[]{ String.valueOf(msgId) })>0;
}
@Override
public int updateMsg(Msg msg) throws SQLException
{
// 定义日期时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sql = "update msg set MSG_CONTENT = ? , MSG_SENDFROM = ? ,MSG_SENDTO =?"
+",MSG_REMARK = ? ,MSG_TYPE = ? where msg_id = ?";
String[] strArr = new String[]
{ msg.getMsgContent(), String.valueOf(msg.getSendFrom()),
String.valueOf(msg.getSendTo()), msg.getRemark(), msg.getMsgTye(),
String.valueOf(msg.getMsgId()) };
// System.out.println(new java.util.Date());
return jdbc.update(sql, strArr);
}
@Override
public Msg selectAMsg(int msgId)
{
ResultSet rs = null;
String sql = "select * from MSG where MSG_ID = ?";
rs = jdbc.query(sql, new String[]
{ String.valueOf(msgId) });
try
{
if (rs.next())
{
String msgContent = rs.getString("MSG_CONTENT");
int sendFrom = rs.getInt("MSG_SENDFROM");
int sendTo = rs.getInt("MSG_SENDTO");
String sendTime = rs.getString("MSG_SENDTIME");
String remark = rs.getString("MSG_REMARK");
String msgType = rs.getString("MSG_TYPE");
Msg msg = new Msg(msgContent, sendFrom, sendTo, sendTime,
remark, msgType);
return msg;
}
else
return null;
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
finally
{
jdbc.closeConnection();
}
}
@Override
public ArrayList<Msg> selectMsgs(String sql)
{
ArrayList<Msg> list = new ArrayList<Msg>();
ResultSet rs = null;
rs = jdbc.query(sql, null);
try
{
while (rs.next())
{
int msg_id = rs.getInt(1);
String msgContent = rs.getString(2);
int sendFrom = rs.getInt(3);
int sendTo = rs.getInt(4);
String sendTime = rs.getString(5);
String remark = rs.getString(6);
String msgType = rs.getString(7);
Msg msg = new Msg(msg_id, msgContent, sendFrom, sendTo,
sendTime, remark, msgType);
list.add(msg);
}
return list;
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
finally
{
jdbc.closeConnection();
}
}
/*public ArrayList<Msg> QueryMessageBySendTO(int sendTo)
{
return selectMsgs("select * from MSG where MSG_SENDTO = "+sendTo);
}*/
public boolean deleteMsgBySendTO(int sendto)
{
try
{
String sql = "delete from msg where msg_sendto = ?";
return jdbc.update(sql, new String[]{ sendto+""})>0;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
/**
* WZQ写的
* @param sendto
* @return
*/
public List<Msg> selectMsgBySendTo(int sendto)
{
ResultSet rs = null;
String sql = "select * from MSG where MSG_SENDTO = ?";
List<Msg> list=new ArrayList<Msg>();
rs = jdbc.query(sql, new String[]
{ String.valueOf(sendto) });
try
{
while (rs.next())
{
String msgContent = rs.getString("MSG_CONTENT");
int sendFrom = rs.getInt("MSG_SENDFROM");
int sendTo = rs.getInt("MSG_SENDTO");
String sendTime = rs.getString("MSG_SENDTIME");
String remark = rs.getString("MSG_REMARK");
String msgType = rs.getString("MSG_TYPE");
Msg msg = new Msg(msgContent, sendFrom, sendTo, sendTime,
remark, msgType);
list.add(msg);
}
return list;
}
catch (SQLException e)
{
e.printStackTrace();
return null;
}
finally
{
}
}
}
================================================
FILE: src/server/dao/UserDao.java
================================================
package server.dao;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import server.common.JDBC;
import server.entity.Users;
public class UserDao implements IUser {
JDBC con = new JDBC();
@Override
public boolean add(Users user) throws SQLException
{
Date birth = user.getBirthday();
String sql="insert into users(u_name,u_pwd,u_gender,u_email,u_remarke,u_signature,u_head_Img,u_type,u_birthday) values (?,?,?,?,?,?,?,?,?)";
String[] params={user.getName(),user.getPwd(),user.getGender(),user.getEmail(),user.getRemarke(),user.getSignature(),user.getHeadImg(),user.getType(),user.getBirthday().toString()};
return con.update(sql,params)>0;
}
@Override
public boolean delete(int usersid) throws SQLException
{
String sql="delete from users where U_ID =?";
if(con.update(sql, new String[]{String.valueOf(usersid)})>0)
{
return true;
}
else
{
return false;
}
}
public boolean update(Users user)
{
int result = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.format(user.getBirthday().getTime());
try
{
result = con.update("update users set u_name = ?, u_pwd = ?, u_gender = ?, " +
"u_email = ?," +
" u_remarke = ?, u_signature = ?, u_head_img = ?, u_type = ?," +
" u_birthday = to_date('"+user.getBirthday()+"','yyyy-mm-dd') where u_id = ?", new String[]{user.getName(),
user.getPwd(),user.getGender(),user.getEmail()
,user.getRemarke(),
user.getSignature(),user.getHeadImg(),user.getType(),
String.valueOf(user.getId())});
}
catch (Exception e)
{
e.printStackTrace();
}
return result>0;
}
@Override
public ArrayList<Users> queryAll()
{
Users user = null;
ArrayList<Users> list = new ArrayList<Users>();
ResultSet rs = con.query("select * from users order by u_id", null);
try
{
// 开始遍历获取数据
while (rs.next())
{
user = new Users();// 如果找到数据,创建用户对象
user.setId(rs.getInt("u_id"));
user.setName(rs.getString("u_name"));
user.setPwd(rs.getString("u_pwd"));
user.setGender(rs.getString("u_gender"));
user.setEmail(rs.getString("u_email"));
user.setLastLogin(rs.getString("u_last_login"));
user.setLastExit(rs.getString("u
gitextract_tbbip7i2/
├── .classpath
├── .gitignore
├── .project
├── .settings/
│ └── org.eclipse.jdt.core.prefs
├── LICENSE
├── README.md
├── lib/
│ ├── AbsoluteLayout.jar
│ ├── mysql-connector-java-5.0.4-bin.jar
│ └── swing-layout-1.0.3.jar
├── myqq.sql
└── src/
├── client/
│ ├── common/
│ │ ├── ComboBoxRenderer.java
│ │ ├── MyLabel.java
│ │ ├── MyTextPane.java
│ │ └── MyTreeIcon.java
│ ├── control/
│ │ ├── Chat.java
│ │ ├── Login.java
│ │ ├── Main.java
│ │ ├── MyTree.java
│ │ ├── QunChat.java
│ │ ├── RecieveThread.java
│ │ ├── Register.java
│ │ └── SendTread.java
│ ├── frame/
│ │ ├── ChatFrame.form
│ │ ├── ChatFrame.java
│ │ ├── FaceFrame.java
│ │ ├── LoginFrame.java
│ │ ├── MainFrame.java
│ │ ├── MyPanel.java
│ │ ├── PublicMessageFrame.java
│ │ ├── QunChatFrame.java
│ │ ├── RegisterFrame.java
│ │ ├── ScreenFram.java
│ │ └── SendFileFrame.java
│ └── socket/
│ ├── CC_TCP.java
│ ├── CS_TCP.java
│ ├── S_TCP.java
│ └── UDPChat.java
├── com/
│ ├── MyTools.java
│ └── socket/
│ ├── TCP.java
│ ├── TCPServer.java
│ └── UDP.java
├── log4j-1.2.dtd
├── log4j.xml
└── server/
├── QQServer.java
├── common/
│ ├── JDBC.java
│ ├── Page.java
│ └── PageService.java
├── dao/
│ ├── IMsg.java
│ ├── IUser.java
│ ├── MsgDao.java
│ └── UserDao.java
├── entity/
│ ├── Msg.java
│ └── Users.java
└── frame/
├── MainWindow.java
├── MsgActionListener.java
├── MsgMana.java
├── ServerActionListen.java
├── ServerMana.java
├── UserActionListen.java
├── UserMana.java
└── UserTableCahnged.java
SYMBOL INDEX (410 symbols across 49 files)
FILE: myqq.sql
type `msg` (line 22) | CREATE TABLE `msg` (
type `users` (line 41) | CREATE TABLE `users` (
FILE: src/client/common/ComboBoxRenderer.java
class ComboBoxRenderer (line 13) | public class ComboBoxRenderer extends JLabel implements ListCellRenderer
method ComboBoxRenderer (line 18) | public ComboBoxRenderer(ImageIcon[] images,String[] imageNames)
method getListCellRendererComponent (line 31) | public Component getListCellRendererComponent(JList list, Object value,
method setUhOhText (line 67) | protected void setUhOhText(String uhOhText, Font normalFont)
FILE: src/client/common/MyLabel.java
class MyLabel (line 10) | public class MyLabel
method MyLabel (line 24) | public MyLabel(JLabel jLabel,String fileName,String extension)
method MyLabel (line 30) | public MyLabel(JLabel jLabel)
method MyLabel (line 37) | public MyLabel(JLabel jLabel,Color color)
method setEtchedBorder (line 49) | public void setEtchedBorder(Color color)
method addEvent (line 56) | public void addEvent()
FILE: src/client/common/MyTextPane.java
class MyTextPane (line 17) | public class MyTextPane
method MyTextPane (line 22) | public MyTextPane(JTextPane textPane)
method addText (line 27) | public void addText(String text,SimpleAttributeSet font)
method addIcon (line 39) | public void addIcon(String imagePath,String friendName)
method addIcon (line 59) | public void addIcon(Image image,String friendName)
method getFontAttribute (line 83) | public static SimpleAttributeSet getFontAttribute(String name, int siz...
method getMyAttribute (line 94) | public static SimpleAttributeSet getMyAttribute()
method getFriendAttribute (line 98) | public static SimpleAttributeSet getFriendAttribute()
method getTimeAttribute (line 102) | public static SimpleAttributeSet getTimeAttribute()
FILE: src/client/common/MyTreeIcon.java
class MyTreeIcon (line 19) | public class MyTreeIcon extends DefaultTreeCellRenderer
method MyTreeIcon (line 25) | public MyTreeIcon(ArrayList<String> nodeImages)
method getTreeCellRendererComponent (line 30) | public Component getTreeCellRendererComponent(
FILE: src/client/control/Chat.java
class Chat (line 56) | public class Chat extends ChatFrame
method Chat (line 99) | public Chat(String friendIP,int friendTCPPort,String friendName,String...
method Chat (line 123) | public Chat(TCP tcp,String friendName,String myName)
method Chat (line 137) | public Chat(CS_TCP cs_TCP,String friendName)
method init (line 145) | public void init()
method initGetFileServer (line 174) | public void initGetFileServer()
method initLabelEvent (line 223) | public void initLabelEvent()
method sendMessage (line 242) | @Override
method setSendPaneText (line 334) | public void setSendPaneText(String text)
method setReceivePaneText (line 351) | public void setReceivePaneText(boolean isFromMyself, String text)
method sendFile (line 369) | public void sendFile()
method beforeClose (line 384) | public void beforeClose()
method selectFace (line 388) | public void selectFace()
method sendImg (line 395) | public void sendImg()
method screenFram (line 467) | @Override
FILE: src/client/control/Login.java
class Login (line 22) | public class Login extends LoginFrame
method main (line 38) | public static void main(String[] args)
method Login (line 48) | public Login()
method init (line 56) | public void init()
method initUserStatus (line 74) | public void initUserStatus()
method login (line 88) | public void login()
method mousePress (line 115) | public void mousePress(MouseEvent e)
method mouseDrag (line 123) | public void mouseDrag(MouseEvent e)
method addEvent (line 138) | public void addEvent()
FILE: src/client/control/Main.java
class Main (line 21) | public class Main extends MainFrame
method Main (line 29) | public Main()
method Main (line 34) | public Main(CS_TCP cs_TCP)
method init (line 43) | public void init()
method setCS_TCP (line 55) | public void setCS_TCP(CS_TCP cs_TCP)
method getServerPort (line 59) | public int getServerPort()
method initUserStatus (line 66) | public void initUserStatus()
method initjTree (line 78) | public void initjTree(String[] groupNames,ArrayList<String[]> friendNa...
method startChat (line 86) | @Override
method getFriendInfo (line 114) | @Override
method sendFile (line 125) | @Override
method deleteFriend (line 133) | public void deleteFriend(ActionEvent e)
method gotoChatRoom (line 142) | @Override
method buildNewChatRoom (line 150) | @Override
FILE: src/client/control/MyTree.java
class MyTree (line 18) | public class MyTree
method MyTree (line 25) | public MyTree(JTree tree,String[] groupNames,ArrayList<String[]> frien...
method MyTree (line 33) | public MyTree(JTree tree)
method init (line 42) | public void init()
method setNodeImage (line 79) | public void setNodeImage()
method addEvent (line 90) | public void addEvent()
method addGroupToTree (line 124) | public void addGroupToTree(String groupName)
method addFriendToTree (line 135) | public void addFriendToTree(String groupName,String friendName)
method deleteFriend (line 151) | public void deleteFriend(String groupName,String friendName)
method openGroup (line 177) | public void openGroup(String groupName)
FILE: src/client/control/QunChat.java
class QunChat (line 22) | public class QunChat extends QunChatFrame
method QunChat (line 27) | public QunChat(Main main)
method addEvent (line 38) | public void addEvent()
method receiveMessage (line 59) | public void receiveMessage(String message)
method showPublicMessage (line 73) | public void showPublicMessage(String message)
FILE: src/client/control/RecieveThread.java
class RecieveThread (line 17) | public class RecieveThread extends Thread
method RecieveThread (line 26) | public RecieveThread(SendFileFrame fram, Socket socket)
method run (line 33) | @Override
method recieveFile (line 40) | public void recieveFile()
method closeRecieve (line 130) | public void closeRecieve()
FILE: src/client/control/Register.java
class Register (line 26) | public class Register extends RegisterFrame
method Register (line 32) | public Register()
method initHeadImage (line 44) | public void initHeadImage()
method addEvent (line 51) | public void addEvent()
method beforeClose (line 94) | @Override
method cancle (line 103) | @Override
method actionPerformed (line 110) | public void actionPerformed(ActionEvent e)
FILE: src/client/control/SendTread.java
class SendTread (line 16) | public class SendTread extends Thread
method SendTread (line 27) | public SendTread(SendFileFrame fram, String Filepath,String connIP,int...
method run (line 35) | @Override
method startSend (line 42) | public void startSend(String filepath)
method closeSend (line 98) | public void closeSend()
FILE: src/client/frame/ChatFrame.java
class ChatFrame (line 21) | public class ChatFrame extends javax.swing.JFrame
method ChatFrame (line 25) | public ChatFrame()
method initComponents (line 37) | private void initComponents()
method formWindowClosing (line 467) | private void formWindowClosing(java.awt.event.WindowEvent evt)
method jLabel发送文件MouseClicked (line 473) | private void jLabel发送文件MouseClicked(java.awt.event.MouseEvent evt)
method jButton发送ActionPerformed (line 479) | private void jButton发送ActionPerformed(java.awt.event.ActionEvent evt)
method getjTextPane聊天记录 (line 516) | public javax.swing.JTextPane getjTextPane聊天记录()
method setjTextPane聊天记录 (line 521) | public void setjTextPane聊天记录(javax.swing.JTextPane jTextPane聊天记录)
method sendMessage (line 529) | public void sendMessage()
method beforeClose (line 533) | public void beforeClose(){}
method selectFace (line 537) | public void selectFace(){}
method dealIcon (line 541) | public void dealIcon(String str)
method sendFile (line 548) | public void sendFile()
method sendImg (line 557) | public void sendImg()
method screenFram (line 564) | public void screenFram()
FILE: src/client/frame/FaceFrame.java
class FaceFrame (line 18) | public class FaceFrame extends JWindow
method FaceFrame (line 28) | public FaceFrame(Chat chat)
method jbInit (line 46) | private void jbInit() throws Exception
method getObj (line 83) | private JWindow getObj()
FILE: src/client/frame/LoginFrame.java
class LoginFrame (line 21) | public class LoginFrame extends JFrame
method main (line 42) | public static void main(String[] args)
method LoginFrame (line 65) | public LoginFrame()
FILE: src/client/frame/MainFrame.java
class MainFrame (line 42) | public class MainFrame extends JFrame
method MainFrame (line 68) | public MainFrame()
method addPopup (line 224) | private static void addPopup(Component component, final JPopupMenu pop...
method startChat (line 244) | public void startChat(ActionEvent e)
method getFriendInfo (line 251) | public void getFriendInfo(ActionEvent e)
method sendFile (line 259) | public void sendFile(ActionEvent e)
method deleteFriend (line 267) | public void deleteFriend(ActionEvent e)
method gotoChatRoom (line 274) | public void gotoChatRoom()
method buildNewChatRoom (line 280) | public void buildNewChatRoom()
FILE: src/client/frame/MyPanel.java
class MyPanel (line 8) | public class MyPanel extends JPanel
method MyPanel (line 11) | public MyPanel(String imagePath)
method paintComponent (line 16) | @Override
FILE: src/client/frame/PublicMessageFrame.java
class PublicMessageFrame (line 26) | public class PublicMessageFrame extends JDialog
method main (line 38) | public static void main(String[] args)
method PublicMessageFrame (line 46) | public PublicMessageFrame(String title,String publicMessage)
method PublicMessageFrame (line 53) | public PublicMessageFrame(String title,String publicMessage,Chat chat)
method init (line 58) | public void init(String title,String publicMessage)
method addEvent (line 122) | public void addEvent()
method showFrame (line 138) | public void showFrame()
method showChat (line 171) | public void showChat()
FILE: src/client/frame/QunChatFrame.java
class QunChatFrame (line 28) | public class QunChatFrame extends JFrame
method main (line 41) | public static void main(String[] args)
method QunChatFrame (line 63) | public QunChatFrame()
FILE: src/client/frame/RegisterFrame.java
class RegisterFrame (line 38) | public class RegisterFrame extends JFrame {
method RegisterFrame (line 53) | public RegisterFrame()
method beforeClose (line 173) | public void beforeClose()
method cancle (line 178) | public void cancle()
FILE: src/client/frame/ScreenFram.java
class ScreenFram (line 34) | public class ScreenFram
method main (line 36) | public static void main()
class RectD (line 48) | class RectD extends JFrame
method paint (line 61) | @Override
method RectD (line 69) | public RectD()
method saveToFile (line 118) | public void saveToFile()
method snapshot (line 137) | public void snapshot()
FILE: src/client/frame/SendFileFrame.java
class SendFileFrame (line 24) | public class SendFileFrame extends JFrame
method SendFileFrame (line 36) | public SendFileFrame()
method updateProgressBar (line 65) | public void updateProgressBar(JProgressBar bar, long passlen, long sum...
method showDialog (line 86) | public String showDialog(int seletMode)
FILE: src/client/socket/CC_TCP.java
class CC_TCP (line 17) | public class CC_TCP extends TCP
method CC_TCP (line 20) | public CC_TCP(String serverIP, int serverPort,Chat chat) throws Exception
method dealWithMessage (line 26) | @Override
method dealWithExit (line 38) | @Override
method showMessage (line 42) | public void showMessage(String message)
method doStartSendFile (line 46) | public void doStartSendFile(String message)
method doFace (line 51) | public void doFace(String message)
FILE: src/client/socket/CS_TCP.java
class CS_TCP (line 25) | public class CS_TCP extends TCP
method CS_TCP (line 29) | public CS_TCP(String serverIP, int serverPort, Login login,Main main) ...
method CS_TCP (line 41) | public CS_TCP(String serverIP, int serverPort) throws Exception
method dealWithMessage (line 47) | @Override
method dealWithExit (line 66) | @Override
method doLogin (line 75) | public void doLogin(String message)
method doRegister (line 93) | public void doRegister(String message)
method doUsersInfo (line 105) | public void doUsersInfo(String message)
method doGetFriendInfo (line 120) | public void doGetFriendInfo(String message)
method doFriendList (line 124) | public void doFriendList(String message)
method doQunChat (line 141) | public void doQunChat(String message)
method doPublicMessage (line 156) | public void doPublicMessage(String message)
method doShowWindow (line 166) | public void doShowWindow(String message)
method doUnreadMessage (line 182) | public void doUnreadMessage(String message)
FILE: src/client/socket/S_TCP.java
class S_TCP (line 31) | public class S_TCP extends TCPServer
method S_TCP (line 35) | public S_TCP(int serverPort,Main main)
method dealWithMessage (line 45) | @Override
method dogetImg (line 64) | private void dogetImg(String message,TCP tcp)
method dealWithExit (line 81) | @Override
method afterServerStart (line 89) | @Override
method doStartChat (line 93) | public void doStartChat(String message,TCP tcp)
method showMessage (line 107) | public void showMessage(String message,TCP tcp)
method doSendFile (line 126) | public void doSendFile(String message,TCP tcp)
method doFace (line 142) | public void doFace(String message,TCP tcp)
FILE: src/client/socket/UDPChat.java
class UDPChat (line 8) | public class UDPChat extends UDP
method UDPChat (line 12) | public UDPChat(String friendIP, Chat parent)
method newThreadGetMessage (line 22) | public void newThreadGetMessage()
FILE: src/com/MyTools.java
class MyTools (line 21) | public class MyTools
type Flag (line 46) | public enum Flag
method setWindowsMiddleShow (line 72) | public static void setWindowsMiddleShow(JFrame frame)
method setWindowsMiddleShow (line 83) | public static void setWindowsMiddleShow(JFrame frame,int width,int hei...
method changeSkin (line 92) | public static void changeSkin()
method getIcon (line 112) | public static ImageIcon getIcon(String path)
method stringToFlagEnum (line 133) | public static Flag stringToFlagEnum(String str)
method getFaceByIdx (line 137) | public static String getFaceByIdx(int idx)
method playMsgSound (line 156) | public static void playMsgSound()
method playSystemSound (line 169) | public static void playSystemSound()
FILE: src/com/socket/TCP.java
class TCP (line 24) | public class TCP
method TCP (line 38) | public TCP(String serverIP, int serverPort) throws Exception
method TCP (line 49) | public TCP(ServerSocket server)
method closeSocket (line 65) | public void closeSocket()
method getMessageNewThread (line 81) | public void getMessageNewThread()
method dealWithMessage (line 111) | public void dealWithMessage(Flag flag,String message)
method dealWithExit (line 115) | public void dealWithExit()
method sendMessage (line 124) | public void sendMessage(String text)
method getMessage (line 143) | public String getMessage() throws Exception
method sendFile (line 151) | public void sendFile()
method sendImg (line 160) | public void sendImg(String imgPath)
method getImg (line 214) | public void getImg(Chat chat ,String imgName)
method getClientIP (line 263) | public String getClientIP()
method getLocalHostIP (line 272) | public static String getLocalHostIP()
method getClientName (line 287) | public String getClientName()
method setClientName (line 295) | public void setClientName(String name)
method getClientServerPort (line 304) | public int getClientServerPort()
method setClientServerPort (line 313) | public void setClientServerPort(int clientServerPort)
method getServerPort (line 321) | public int getServerPort()
method getClientPort (line 325) | public int getClientPort()
method setUserState (line 333) | public void setUserState(int userState)
method getUserState (line 341) | public int getUserState()
FILE: src/com/socket/TCPServer.java
class TCPServer (line 11) | public class TCPServer
method TCPServer (line 22) | public TCPServer(int serverPort)
method closeServer (line 35) | public void closeServer()
method startServerTCP (line 50) | public boolean startServerTCP()
method getConnectionNewThread (line 86) | public void getConnectionNewThread()
method getMessageNewThread (line 107) | public void getMessageNewThread(final TCP tcp)
method dealWithMessage (line 146) | public void dealWithMessage(Flag flag,String message,TCP tcp)
method dealWithExit (line 154) | public void dealWithExit(TCP tcp)
method afterServerStart (line 161) | public void afterServerStart()
method getServerPort (line 165) | public int getServerPort()
FILE: src/com/socket/UDP.java
class UDP (line 11) | public class UDP
method UDP (line 18) | public UDP(String friendIP)
method setFriendPort (line 35) | public void setFriendPort(int friendPort)
method getMyPort (line 44) | public int getMyPort()
method getMyUsefulPort (line 51) | public void getMyUsefulPort()
method sendMessage (line 70) | public void sendMessage(String text)
method getMessage (line 89) | public String getMessage()
method newThreadGetMessage (line 109) | public void newThreadGetMessage()
FILE: src/server/QQServer.java
class QQServer (line 23) | public class QQServer extends TCPServer
method QQServer (line 28) | public QQServer(int serverPort)
method dealWithMessage (line 49) | @Override
method dealWithExit (line 67) | @Override
method afterServerStart (line 80) | @Override
method doLogin (line 91) | public void doLogin(String message,TCP tcp)
method doGetFriendInfo (line 146) | public void doGetFriendInfo(String message,TCP tcp)
method doRegister (line 167) | public void doRegister(String message,TCP tcp)
method checkNameAndPwd (line 213) | public boolean checkNameAndPwd(String name,String password)
method checkIsLoginAgain (line 225) | public boolean checkIsLoginAgain(String name)
method initClientInfo (line 240) | public void initClientInfo(TCP tcp)
method refreshAllUserFriendList (line 248) | public void refreshAllUserFriendList()
method getCurrentUserInfo (line 259) | public String getCurrentUserInfo(TCP tcp)
method getAllUsersInfo (line 276) | public String getAllUsersInfo()
method showOnlineNumber (line 324) | public void showOnlineNumber()
method doQunChat (line 329) | public void doQunChat(String message,TCP tcp)
method doUnderlineMessage (line 340) | public void doUnderlineMessage(String message,TCP tcp)
method sendUnreadMessage (line 359) | public void sendUnreadMessage(TCP tcp)
method sendPublicMessage (line 387) | public void sendPublicMessage(String message)
method sendShowWindow (line 397) | public void sendShowWindow(String message)
FILE: src/server/common/JDBC.java
class JDBC (line 17) | public class JDBC
method JDBC (line 26) | public JDBC()
method JDBC (line 37) | public JDBC(String url,String user,String password)
method getConnection (line 49) | private Connection getConnection(String url,String user,String password)
method getConnection (line 69) | private Connection getConnection()
method closeConnection (line 76) | public void closeConnection()
method update (line 100) | public int update(String sql,String[] params) throws SQLException
method query (line 119) | public ResultSet query(String sql,String[] params)
method writeProperties (line 143) | public static void writeProperties(String url,String user,String passw...
method readProperties (line 177) | public static List readProperties()
FILE: src/server/common/Page.java
class Page (line 3) | public class Page {
method getTotalRecords (line 8) | public int getTotalRecords() {
method setTotalRecords (line 11) | public void setTotalRecords(int totalRecords) {
method getTotalPage (line 14) | public int getTotalPage() {
method setTotalPage (line 17) | public void setTotalPage(int totalPage) {
method getPageSize (line 20) | public int getPageSize() {
method setPageSize (line 23) | public void setPageSize(int pageSize) {
method getCurrentPage (line 26) | public int getCurrentPage() {
method setCurrentPage (line 29) | public void setCurrentPage(int currentPage) {
FILE: src/server/common/PageService.java
class PageService (line 5) | public class PageService {
method PageService (line 8) | public PageService(List listAll) {
method initPage (line 16) | private void initPage() {
method gotoPage (line 48) | public List gotoPage(int target) {
method gotoFirst (line 67) | public List gotoFirst(){
method gotoNext (line 74) | public List gotoNext(){
method gotoPre (line 81) | public List gotoPre(){
method gotoLast (line 89) | public List gotoLast(){
method getTotalPage (line 92) | public int getTotalPage()
method getCurrentPage (line 96) | public int getCurrentPage()
method getTotalRecord (line 100) | public int getTotalRecord()
method getPageSize (line 104) | public int getPageSize()
FILE: src/server/dao/IMsg.java
type IMsg (line 8) | public interface IMsg
method insertMsg (line 10) | public boolean insertMsg(Msg msg)throws SQLException;
method deleteMsg (line 11) | public boolean deleteMsg(int msgId)throws SQLException;
method updateMsg (line 12) | public int updateMsg(Msg msg)throws SQLException;
method selectAMsg (line 13) | public Msg selectAMsg(int msgId);
method selectMsgs (line 14) | public List<Msg> selectMsgs(String sql);
FILE: src/server/dao/IUser.java
type IUser (line 15) | public interface IUser {
method queryById (line 20) | public Users queryById(int usersid) ;
method queryAll (line 24) | public List<Users> queryAll() ;
method add (line 30) | public boolean add(Users user)throws SQLException;
method update (line 35) | public boolean update(Users user)throws SQLException;
method delete (line 40) | public boolean delete(int usersid)throws SQLException;
method checkUserIsExit (line 46) | public boolean checkUserIsExit(String name);
method checkNameAndPwd (line 53) | public boolean checkNameAndPwd(String name,String password);
method updateUserState (line 60) | public boolean updateUserState(String name,String state);
method queryByName (line 65) | public Users queryByName(String name);
FILE: src/server/dao/MsgDao.java
class MsgDao (line 19) | public class MsgDao implements IMsg
method insertMsg (line 23) | public boolean insertMsg(Msg msg) throws SQLException
method deleteMsg (line 34) | @Override
method updateMsg (line 41) | @Override
method selectAMsg (line 57) | @Override
method selectMsgs (line 96) | @Override
method deleteMsgBySendTO (line 138) | public boolean deleteMsgBySendTO(int sendto)
method selectMsgBySendTo (line 156) | public List<Msg> selectMsgBySendTo(int sendto)
FILE: src/server/dao/UserDao.java
class UserDao (line 13) | public class UserDao implements IUser {
method add (line 16) | @Override
method delete (line 25) | @Override
method update (line 39) | public boolean update(Users user)
method queryAll (line 62) | @Override
method queryById (line 103) | public Users queryById(int usersid)
method queryByName (line 136) | public Users queryByName(String userName)
method checkUserIsExit (line 174) | @Override
method checkNameAndPwd (line 194) | @Override
method updateUserState (line 216) | @Override
method setLastLogin (line 231) | public void setLastLogin(String name)
method setLastExit (line 241) | public void setLastExit(String name)
method setUserState (line 251) | public void setUserState(String name,int i)
method setIP (line 263) | public void setIP(String IP,String name)
FILE: src/server/entity/Msg.java
class Msg (line 5) | public class Msg
method toString (line 15) | @Override
method Msg (line 34) | public Msg(String msgContent, int sendFrom, int sendTo, String remark,
method Msg (line 59) | public Msg(int msgId, String msgContent, int sendFrom, int sendTo,
method Msg (line 83) | public Msg(int msgId, String msgContent, int sendFrom, int sendTo,
method Msg (line 105) | public Msg(String msgContent, int sendFrom, int sendTo, String sendTime,
method Msg (line 116) | public Msg()
method getMsgId (line 121) | public int getMsgId()
method setMsgId (line 125) | public void setMsgId(int msgId)
method getMsgContent (line 129) | public String getMsgContent()
method setMsgContent (line 133) | public void setMsgContent(String msgContent)
method getSendFrom (line 137) | public int getSendFrom()
method setSendFrom (line 141) | public void setSendFrom(int sendFrom)
method getSendTo (line 145) | public int getSendTo()
method setSendTo (line 149) | public void setSendTo(int sendTo)
method getSendTime (line 153) | public String getSendTime()
method setSendTime (line 157) | public void setSendTime(String sendTime)
method getRemark (line 161) | public String getRemark()
method setRemark (line 165) | public void setRemark(String remark)
method getMsgTye (line 169) | public String getMsgTye()
method setMsgTye (line 173) | public void setMsgTye(String msgTye)
FILE: src/server/entity/Users.java
class Users (line 12) | public class Users
method Users (line 30) | public Users()
method Users (line 48) | public Users(int id, String name, String pwd, String gender, String em...
method Users (line 80) | public Users(String name, String pwd, String gender, String email,
method Users (line 93) | public Users(int id, String name, String pwd, String gender, String em...
method getState (line 106) | public String getState() {
method setState (line 112) | public void setState(String state) {
method getIp (line 118) | public String getIp() {
method setIp (line 124) | public void setIp(String ip) {
method getType (line 130) | public String getType() {
method setType (line 136) | public void setType(String type) {
method getBirthday (line 142) | public Date getBirthday() {
method setBirthday (line 148) | public void setBirthday(Date birthday) {
method getId (line 154) | public int getId() {
method setId (line 160) | public void setId(int id) {
method getName (line 166) | public String getName() {
method setName (line 172) | public void setName(String name) {
method getPwd (line 178) | public String getPwd() {
method setPwd (line 184) | public void setPwd(String pwd) {
method getGender (line 190) | public String getGender() {
method setGender (line 196) | public void setGender(String gender) {
method getEmail (line 202) | public String getEmail() {
method setEmail (line 208) | public void setEmail(String email) {
method getLastLogin (line 214) | public String getLastLogin() {
method setLastLogin (line 220) | public void setLastLogin(String lastLogin) {
method getLastExit (line 226) | public String getLastExit() {
method setLastExit (line 232) | public void setLastExit(String lastExit) {
method getRemarke (line 238) | public String getRemarke() {
method setRemarke (line 244) | public void setRemarke(String remarke) {
method getSignature (line 250) | public String getSignature() {
method setSignature (line 256) | public void setSignature(String signature) {
method getHeadImg (line 262) | public String getHeadImg() {
method setHeadImg (line 268) | public void setHeadImg(String headImg) {
FILE: src/server/frame/MainWindow.java
class MainWindow (line 23) | public class MainWindow extends JFrame {
method main (line 34) | public static void main(String[] args)
method MainWindow (line 43) | public MainWindow()
FILE: src/server/frame/MsgActionListener.java
class MsgActionListener (line 17) | public class MsgActionListener implements ActionListener
method MsgActionListener (line 24) | public MsgActionListener(MsgMana msgMana)
method actionPerformed (line 33) | public void actionPerformed(ActionEvent e)
FILE: src/server/frame/MsgMana.java
class MsgMana (line 25) | public class MsgMana extends JPanel {
method MsgMana (line 32) | public MsgMana()
method refresh (line 149) | public List refresh()
FILE: src/server/frame/ServerActionListen.java
class ServerActionListen (line 12) | public class ServerActionListen implements ActionListener{
method ServerActionListen (line 16) | public ServerActionListen(ServerMana serverMana)
method actionPerformed (line 20) | public void actionPerformed(ActionEvent e)
FILE: src/server/frame/ServerMana.java
class ServerMana (line 32) | public class ServerMana extends JPanel implements Runnable
method ServerMana (line 54) | public ServerMana()
method run (line 158) | public void run()
method showTime (line 179) | public void showTime()
method showRunTime (line 191) | public void showRunTime()
method startOrCloseServer (line 196) | public void startOrCloseServer()
method sendPublicMessage (line 222) | public void sendPublicMessage()
method showWindow (line 239) | public void showWindow()
FILE: src/server/frame/UserActionListen.java
class UserActionListen (line 15) | public class UserActionListen implements ActionListener
method UserActionListen (line 21) | public UserActionListen(UserMana userMana)
method actionPerformed (line 29) | public void actionPerformed(ActionEvent e)
FILE: src/server/frame/UserMana.java
class UserMana (line 29) | public class UserMana extends JPanel {
method UserMana (line 47) | public UserMana()
method refresh (line 180) | public List refresh()
FILE: src/server/frame/UserTableCahnged.java
class UserTableCahnged (line 16) | public class UserTableCahnged implements TableModelListener {
method UserTableCahnged (line 18) | public UserTableCahnged(JTable table)
method tableChanged (line 22) | public void tableChanged(TableModelEvent e) {
Condensed preview — 61 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (288K chars).
[
{
"path": ".classpath",
"chars": 426,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<classpath>\n\t<classpathentry kind=\"src\" path=\"src\"/>\n\t<classpathentry kind=\"con\" "
},
{
"path": ".gitignore",
"chars": 11,
"preview": "*.class\nbin"
},
{
"path": ".project",
"chars": 363,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<projectDescription>\n\t<name>myqq</name>\n\t<comment></comment>\n\t<projects>\n\t</proje"
},
{
"path": ".settings/org.eclipse.jdt.core.prefs",
"chars": 587,
"preview": "eclipse.preferences.version=1\norg.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled\norg.eclipse.jdt.core.compi"
},
{
"path": "LICENSE",
"chars": 1061,
"preview": "MIT License\n\nCopyright (c) 2017 小茗同学\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof th"
},
{
"path": "README.md",
"chars": 1471,
"preview": "# 说明\n\nJava版SWing“高”仿QQ即时通聊天系统\n\n原贴地址:http://tieba.baidu.com/p/1933997044\n\n首先说明这是一个很老很老的小项目,还是12年的时候写的,代码真的很low很low,low到什"
},
{
"path": "myqq.sql",
"chars": 2259,
"preview": "/*\nNavicat MySQL Data Transfer\n\nSource Server : localhost\nSource Server Version : 50505\nSource Host : "
},
{
"path": "src/client/common/ComboBoxRenderer.java",
"chars": 1860,
"preview": "package client.common;\n\nimport java.awt.Component;\nimport java.awt.Font;\nimport java.awt.Graphics;\nimport java.awt.Imag"
},
{
"path": "src/client/common/MyLabel.java",
"chars": 2122,
"preview": "package client.common;\n\nimport java.awt.Color;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nim"
},
{
"path": "src/client/common/MyTextPane.java",
"chars": 2857,
"preview": "package client.common;\n\nimport java.awt.Color;\nimport java.awt.Image;\nimport java.text.DateFormat;\nimport java.util.Dat"
},
{
"path": "src/client/common/MyTreeIcon.java",
"chars": 1921,
"preview": "package client.common;\n\nimport java.awt.Component;\nimport java.awt.Image;\nimport java.io.File;\nimport java.io.IOExcepti"
},
{
"path": "src/client/control/Chat.java",
"chars": 11173,
"preview": "package client.control;\n\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Graphics;\nimport java.awt.To"
},
{
"path": "src/client/control/Login.java",
"chars": 4697,
"preview": "package client.control;\n\n\nimport java.awt.Point;\nimport java.awt.Rectangle;\nimport java.awt.event.MouseAdapter;\nimport j"
},
{
"path": "src/client/control/Main.java",
"chars": 3498,
"preview": "package client.control;\n\nimport java.awt.event.ActionEvent;\nimport java.awt.event.MouseEvent;\nimport java.util.ArrayLis"
},
{
"path": "src/client/control/MyTree.java",
"chars": 5810,
"preview": "package client.control;\n\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.util.ArrayLi"
},
{
"path": "src/client/control/QunChat.java",
"chars": 2075,
"preview": "package client.control;\n\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.text.Date"
},
{
"path": "src/client/control/RecieveThread.java",
"chars": 3003,
"preview": "package client.control;\n\nimport java.io.DataInputStream;\nimport java.io.DataOutputStream;\nimport java.io.FileOutputStrea"
},
{
"path": "src/client/control/Register.java",
"chars": 3845,
"preview": "package client.control;\n\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event"
},
{
"path": "src/client/control/SendTread.java",
"chars": 2328,
"preview": "package client.control;\n\nimport java.io.DataInputStream;\nimport java.io.DataOutputStream;\nimport java.io.File;\nimport j"
},
{
"path": "src/client/frame/ChatFrame.form",
"chars": 26336,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n\n<Form version=\"1.3\" maxVersion=\"1.5\" type=\"org.netbeans.modules.form.forminfo.J"
},
{
"path": "src/client/frame/ChatFrame.java",
"chars": 18334,
"preview": "/*\n * ChatFrame.java\n *\n * Created on __DATE__, __TIME__\n */\n\npackage client.frame;\n\nimport java.awt.Color;\n\nimport jav"
},
{
"path": "src/client/frame/FaceFrame.java",
"chars": 1981,
"preview": "package client.frame;\n\nimport java.awt.Color;\nimport java.awt.GridLayout;\nimport java.awt.SystemColor;\nimport java.awt."
},
{
"path": "src/client/frame/LoginFrame.java",
"chars": 4407,
"preview": "package client.frame;\n\nimport java.awt.EventQueue;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.s"
},
{
"path": "src/client/frame/MainFrame.java",
"chars": 8624,
"preview": "package client.frame;\n\nimport java.awt.EventQueue;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport java.aw"
},
{
"path": "src/client/frame/MyPanel.java",
"chars": 418,
"preview": "package client.frame;\n\nimport java.awt.Graphics;\nimport java.awt.Image;\nimport javax.swing.JPanel;\nimport com.MyTools;\n"
},
{
"path": "src/client/frame/PublicMessageFrame.java",
"chars": 4303,
"preview": "package client.frame;\n\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Font;\nimport java.awt.Toolkit;\n"
},
{
"path": "src/client/frame/QunChatFrame.java",
"chars": 9110,
"preview": "package client.frame;\n\nimport java.awt.BorderLayout;\nimport java.awt.EventQueue;\n\nimport javax.swing.JFrame;\nimport jav"
},
{
"path": "src/client/frame/RegisterFrame.java",
"chars": 5212,
"preview": "package client.frame;\n\nimport java.awt.Dimension;\nimport java.awt.EventQueue;\nimport java.awt.Image;\nimport java.awt.To"
},
{
"path": "src/client/frame/ScreenFram.java",
"chars": 3241,
"preview": "package client.frame;\n\nimport java.awt.AWTException;\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt."
},
{
"path": "src/client/frame/SendFileFrame.java",
"chars": 2412,
"preview": "package client.frame;\n\nimport java.awt.Color;\nimport java.awt.EventQueue;\nimport java.awt.event.ActionEvent;\nimport jav"
},
{
"path": "src/client/socket/CC_TCP.java",
"chars": 1124,
"preview": "package client.socket;\n\nimport java.text.DateFormat;\nimport java.util.Date;\n\nimport client.common.MyTextPane;\nimport cl"
},
{
"path": "src/client/socket/CS_TCP.java",
"chars": 4717,
"preview": "package client.socket;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.util.ArrayList;\n\nimport javax.s"
},
{
"path": "src/client/socket/S_TCP.java",
"chars": 3243,
"preview": "package client.socket;\n\nimport java.applet.Applet;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io."
},
{
"path": "src/client/socket/UDPChat.java",
"chars": 742,
"preview": "package client.socket;\n\nimport client.control.Chat;\n\nimport com.socket.UDP;\n\n\npublic class UDPChat extends UDP\n{\n\tChat "
},
{
"path": "src/com/MyTools.java",
"chars": 4125,
"preview": "package com;\n\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Toolkit;\nimport java.io.File;\nimport jav"
},
{
"path": "src/com/socket/TCP.java",
"chars": 6271,
"preview": "package com.socket;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport "
},
{
"path": "src/com/socket/TCPServer.java",
"chars": 2993,
"preview": "package com.socket;\n\nimport java.io.IOException;\nimport java.net.ServerSocket;\nimport java.util.ArrayList;\n\nimport com."
},
{
"path": "src/com/socket/UDP.java",
"chars": 2241,
"preview": "package com.socket;\n\nimport java.io.IOException;\nimport java.net.DatagramPacket;\nimport java.net.DatagramSocket;\nimport"
},
{
"path": "src/log4j-1.2.dtd",
"chars": 6718,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!--\n Licensed to the Apache Software Foundation (ASF) under one or more\n contri"
},
{
"path": "src/log4j.xml",
"chars": 1263,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration PUBLIC \"-//APACHE//DTD LOG4J 1.2//EN\" \"log4j-1.2.dt"
},
{
"path": "src/server/QQServer.java",
"chars": 9763,
"preview": "package server;\n\nimport java.sql.Date;\nimport java.sql.SQLException;\nimport java.text.DateFormat;\nimport java.util.Array"
},
{
"path": "src/server/common/JDBC.java",
"chars": 3706,
"preview": "package server.common;\n\nimport java.awt.List;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport ja"
},
{
"path": "src/server/common/Page.java",
"chars": 736,
"preview": "package server.common;\n\npublic class Page {\n\tprivate int totalRecords; //总记录数\n\tprivate int totalPage; //总页数\n\tpriv"
},
{
"path": "src/server/common/PageService.java",
"chars": 2096,
"preview": "package server.common;\n\nimport java.util.ArrayList;\nimport java.util.List;\npublic class PageService {\n\tPage page; //定"
},
{
"path": "src/server/dao/IMsg.java",
"chars": 369,
"preview": "package server.dao;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport server.entity.Msg;\n\npublic interface "
},
{
"path": "src/server/dao/IUser.java",
"chars": 1124,
"preview": "package server.dao;\n\n\n\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport server."
},
{
"path": "src/server/dao/MsgDao.java",
"chars": 4293,
"preview": "package server.dao;\n\n\nimport java.sql.Date;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.text.Si"
},
{
"path": "src/server/dao/UserDao.java",
"chars": 6662,
"preview": "package server.dao;\n\nimport java.sql.Date;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.text.Sim"
},
{
"path": "src/server/entity/Msg.java",
"chars": 3188,
"preview": "package server.entity;\n\nimport java.sql.Date;\n\npublic class Msg\n{\n\tprivate int msgId;\n\tprivate String msgContent;\n\tpriv"
},
{
"path": "src/server/entity/Users.java",
"chars": 4854,
"preview": "package server.entity;\n\n\n\n\nimport java.sql.Date;\n\n/**\n * @author Administrator\n * 用户表的实体类\n */\npublic class Users\n{\n\tpri"
},
{
"path": "src/server/frame/MainWindow.java",
"chars": 2634,
"preview": "package server.frame;\n\nimport java.awt.Dimension;\nimport java.awt.EventQueue;\nimport java.awt.Toolkit;\nimport java.awt."
},
{
"path": "src/server/frame/MsgActionListener.java",
"chars": 2365,
"preview": "package server.frame;\n\nimport java.awt.HeadlessException;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.Acti"
},
{
"path": "src/server/frame/MsgMana.java",
"chars": 5491,
"preview": "package server.frame;\n\n\nimport java.util.List;\nimport java.util.Vector;\n\nimport javax.swing.GroupLayout;\nimport javax.s"
},
{
"path": "src/server/frame/ServerActionListen.java",
"chars": 1081,
"preview": "package server.frame;\n\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JOp"
},
{
"path": "src/server/frame/ServerMana.java",
"chars": 6564,
"preview": "package server.frame;\n\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JButton;\nimport ja"
},
{
"path": "src/server/frame/UserActionListen.java",
"chars": 4591,
"preview": "package server.frame;\n\nimport java.awt.HeadlessException;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.Acti"
},
{
"path": "src/server/frame/UserMana.java",
"chars": 6960,
"preview": "package server.frame;\n\nimport java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.util.List;\nimport java.uti"
},
{
"path": "src/server/frame/UserTableCahnged.java",
"chars": 1454,
"preview": "package server.frame;\n\nimport java.awt.HeadlessException;\nimport java.sql.Date;\nimport java.sql.SQLException;\n\nimport j"
}
]
// ... and 3 more files (download for full content)
About this extraction
This page contains the full source code of the sxei/myqq GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 61 files (231.6 KB), approximately 68.2k tokens, and a symbol index with 410 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.