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
================================================
================================================
FILE: .gitignore
================================================
*.class
bin
================================================
FILE: .project
================================================
myqq
org.eclipse.jdt.core.javabuilder
org.eclipse.jdt.core.javanature
================================================
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 nodeImages=null;
public MyTreeIcon(ArrayList 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 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 nodeImages;//存放节点的头像,示例:张三;02_100.jpg
private ArrayList friendInfos=new ArrayList();//每个分组的好友信息
public MyTree(JTree tree,String[] groupNames,ArrayList 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();
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;i2)//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
================================================
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
//
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();
}//
//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 friendNames=new ArrayList();
for(int i=0;i chats=new ArrayList();//存放所有的打开的聊天窗体集合
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 tcpSockets = new ArrayList();// 存放与客户端的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
================================================
================================================
FILE: src/log4j.xml
================================================
================================================
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 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 msgs=(ArrayList) 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= 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 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 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 selectMsgs(String sql)
{
ArrayList list = new ArrayList();
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 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 selectMsgBySendTo(int sendto)
{
ResultSet rs = null;
String sql = "select * from MSG where MSG_SENDTO = ?";
List list=new ArrayList();
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 queryAll()
{
Users user = null;
ArrayList list = new ArrayList();
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_last_exit"));
user.setRemarke(rs.getString("u_remarke"));
user.setSignature(rs.getString("u_signature"));
user.setHeadImg(rs.getString("u_head_Img"));
user.setBirthday(rs.getDate("u_birthday"));
user.setType(rs.getString("u_type"));
user.setState(rs.getString("u_state"));
user.setIp(rs.getString("u_ip"));
list.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
//con.closeConnection();// 关闭所有数据库对象
}
return list;
}
public Users queryById(int usersid)
{
Users user = null;
ResultSet rs = con.query("select * from users where u_id=? ",
new String[] { String.valueOf(usersid) });
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_last_exit"));
user.setRemarke(rs.getString("u_remarke"));
user.setSignature(rs.getString("u_signature"));
user.setHeadImg(rs.getString("u_head_Img"));
user.setBirthday(rs.getDate("u_birthday"));
user.setType(rs.getString("u_type"));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
//con.closeConnection();// 关闭所有数据库对象
}
return user;
}
public Users queryByName(String userName)
{
Users user = null;
ResultSet rs = con.query("select * from users where u_name=?",
new String[]{userName});
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_last_exit"));
user.setRemarke(rs.getString("u_remarke"));
user.setSignature(rs.getString("u_signature"));
user.setHeadImg(rs.getString("u_head_Img"));
user.setBirthday(rs.getDate("u_birthday"));
user.setType(rs.getString("u_type"));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
//con.closeConnection();// 关闭所有数据库对象
}
return user;
}
/*
* 检测用户是否已存在
*/
@Override
public boolean checkUserIsExit(String name)
{
try
{
ResultSet rs = con.query("select * from users where u_name=? ",
new String[] { name});
if(rs.next())
return true;
else
return false;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
@Override
public boolean checkNameAndPwd(String name, String password)
{
try
{
ResultSet rs = con.query("select * from users where u_name=? and u_pwd=? ",
new String[] { name,password});
if(rs.next())
return true;
else
return false;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
/*
* 更新用户状态
*/
@Override
public boolean updateUserState(String name, String state)
{
int result = 0;
try
{
result = con.update("update users set u_state = ? where u_name = ?",new String[]{state,name});
}
catch (Exception e)
{
e.printStackTrace();
}
return result>0;
}
public void setLastLogin(String name)
{
String sql="update users set u_last_login=CURRENT_TIMESTAMP where u_name=?";
try {
con.update(sql, new String[]{name});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setLastExit(String name)
{
String sql="update users set u_last_exit=CURRENT_TIMESTAMP where u_name=?";
try {
con.update(sql, new String[]{name});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setUserState(String name,int i)
{
String sql="update users set u_state=? where u_name=?";
try
{
con.update(sql, new String[]{String.valueOf(i),name});
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void setIP(String IP,String name)
{
String sql="update users set u_ip=? where u_name=?";
try
{
con.update(sql, new String[]{IP,name});
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
================================================
FILE: src/server/entity/Msg.java
================================================
package server.entity;
import java.sql.Date;
public class Msg
{
private int msgId;
private String msgContent;
private int sendFrom;//信息发送者
private int sendTo;//信息接收者
private String sendTime;//信息发送时间
private String remark;
private String msgTye;//信息类型:离线消息和群公告
@Override
public String toString()
{
// TODO Auto-generated method stub
return "消息的全部信息是:\n"+"msgId:"+msgId+" msgContent:"+msgContent+
" sendFrom:"+sendFrom+" sendTo:"+sendTo+" sendTime :"+sendTime+
" remark:"+remark+" msgTye:"+msgTye;
}
/**
* @param msgContent
* @param sendFrom
* @param sendTo
* @param remark
* @param msgTye
*
* 除msgId 和 sendTime 参数之外 的构造参数
*/
public Msg(String msgContent, int sendFrom, int sendTo, String remark,
String msgTye)
{
super();
this.msgContent = msgContent;
this.sendFrom = sendFrom;
this.sendTo = sendTo;
this.remark = remark;
this.msgTye = msgTye;
}
/**
* @param msgId
* @param msgContent
* @param sendFrom
* @param sendTo
* @param remark
* @param msgTye
*
* 含有除 sendTime参数的 构造函数
*/
public Msg(int msgId, String msgContent, int sendFrom, int sendTo,
String remark, String msgTye)
{
super();
this.msgId = msgId;
this.msgContent = msgContent;
this.sendFrom = sendFrom;
this.sendTo = sendTo;
this.remark = remark;
this.msgTye = msgTye;
}
/**
* @param msgId
* @param msgContent
* @param sendFrom
* @param sendTo
* @param sendTime
* @param remark
* @param msgTye
* 含有全部构造参数
*/
public Msg(int msgId, String msgContent, int sendFrom, int sendTo,
String sendTime, String remark, String msgTye)
{
super();
this.msgId = msgId;
this.msgContent = msgContent;
this.sendFrom = sendFrom;
this.sendTo = sendTo;
this.sendTime = sendTime;
this.remark = remark;
this.msgTye = msgTye;
}
/**
* @param msgContent
* @param sendFrom
* @param sendTo
* @param sendTime
* @param remark
* @param msgTye
* 含有除msgId之外所有参数的构造方法
*/
public Msg(String msgContent, int sendFrom, int sendTo, String sendTime,
String remark, String msgTye)
{
super();
this.msgContent = msgContent;
this.sendFrom = sendFrom;
this.sendTo = sendTo;
this.sendTime = sendTime;
this.remark = remark;
this.msgTye = msgTye;
}
public Msg()
{
// TODO Auto-generated constructor stub
}
public int getMsgId()
{
return msgId;
}
public void setMsgId(int msgId)
{
this.msgId = msgId;
}
public String getMsgContent()
{
return msgContent;
}
public void setMsgContent(String msgContent)
{
this.msgContent = msgContent;
}
public int getSendFrom()
{
return sendFrom;
}
public void setSendFrom(int sendFrom)
{
this.sendFrom = sendFrom;
}
public int getSendTo()
{
return sendTo;
}
public void setSendTo(int sendTo)
{
this.sendTo = sendTo;
}
public String getSendTime()
{
return sendTime;
}
public void setSendTime(String sendTime)
{
this.sendTime = sendTime;
}
public String getRemark()
{
return remark;
}
public void setRemark(String remark)
{
this.remark = remark;
}
public String getMsgTye()
{
return msgTye;
}
public void setMsgTye(String msgTye)
{
this.msgTye = msgTye;
}
}
================================================
FILE: src/server/entity/Users.java
================================================
package server.entity;
import java.sql.Date;
/**
* @author Administrator
* 用户表的实体类
*/
public class Users
{
private int id;//主键
private String name;//姓名
private String pwd;//密码
private String ip;//IP地址
private String state;//状态,-1或空表示不在线,0表示在线,1表示Q我,2表示离开,3表示忙碌,4表示隐身
private String gender;//性别
private String email;//邮箱
private String lastLogin;//最后一次登录
private String lastExit;//最后一次退出
private String remarke;//备用
private String signature;//个性签名
private String headImg;//头像
private String type;//类型
private Date birthday;//生日
public Users()
{
super();
}
/**
* @param id 用户ID
* @param name 用户名
* @param pwd 用户密码
* @param gender 用户性别
* @param email 用户e-mail
* @param lastLogin 用户最后一次登录时间
* @param lastExit 用户最后一次下线时间
* @param remarke 备注
* @param signature 用户签名
* @param headImg 用户头像
* @param birthday 用户生日
* @param type 用户类型(管理员/普通用户)
*/
public Users(int id, String name, String pwd, String gender, String email, String remarke,
String signature, String headImg, Date birthday,String type,String ip,String state) {
super();
this.id = id;
this.name = name;
this.pwd = pwd;
this.gender = gender;
this.email = email;
this.remarke = remarke;
this.signature = signature;
this.headImg = headImg;
this.birthday = birthday;
this.type = type;
this.ip = ip;
this.state = state;
}
/**
* 无用户ID的构造方法
* @param name
* @param pwd
* @param gender
* @param email
* @param lastLogin
* @param lastExit
* @param nickName
* @param remarke
* @param signature
* @param headImg
* @param birthday
*/
public Users(String name, String pwd, String gender, String email,
String signature, String headImg, Date birthday) {
super();
this.name = name;
this.pwd = pwd;
this.gender = gender;
this.email = email;
this.signature = signature;
this.headImg = headImg;
this.birthday = birthday;
this.state=-1+"";//将用户默认状态设为-1表示不在线
}
public Users(int id, String name, String pwd, String gender, String email,
Date birthday) {
super();
this.id = id;
this.name = name;
this.pwd = pwd;
this.gender = gender;
this.email = email;
this.birthday = birthday;
}
/**
* @return the state
*/
public String getState() {
return state;
}
/**
* @param state the state to set
*/
public void setState(String state) {
this.state = state;
}
/**
* @return the ip
*/
public String getIp() {
return ip;
}
/**
* @param ip the ip to set
*/
public void setIp(String ip) {
this.ip = ip;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the birthday
*/
public Date getBirthday() {
return birthday;
}
/**
* @param birthday the birthday to set
*/
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the pwd
*/
public String getPwd() {
return pwd;
}
/**
* @param pwd the pwd to set
*/
public void setPwd(String pwd) {
this.pwd = pwd;
}
/**
* @return the gender
*/
public String getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the lastLogin
*/
public String getLastLogin() {
return lastLogin;
}
/**
* @param lastLogin the lastLogin to set
*/
public void setLastLogin(String lastLogin) {
this.lastLogin = lastLogin;
}
/**
* @return the lastExit
*/
public String getLastExit() {
return lastExit;
}
/**
* @param lastExit the lastExit to set
*/
public void setLastExit(String lastExit) {
this.lastExit = lastExit;
}
/**
* @return the
*/
public String getRemarke() {
return remarke;
}
/**
* @param remarke
*/
public void setRemarke(String remarke) {
this.remarke = remarke;
}
/**
* @return the signature
*/
public String getSignature() {
return signature;
}
/**
* @param signature the signature to set
*/
public void setSignature(String signature) {
this.signature = signature;
}
/**
* @return the headImg
*/
public String getHeadImg() {
return headImg;
}
/**
* @param headImg the headImg to set
*/
public void setHeadImg(String headImg) {
this.headImg = headImg;
}
}
================================================
FILE: src/server/frame/MainWindow.java
================================================
package server.frame;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import client.control.Main;
import com.MyTools;
import javax.swing.ImageIcon;
public class MainWindow extends JFrame {
private JPanel contentPane;
private final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.LEFT);
UserMana userMana;
MsgMana msgMana;
ServerMana serverMana;
/**
* 主方法
*/
public static void main(String[] args)
{
MyTools.changeSkin();
new MainWindow().setVisible(true);
}
/**
* Create the frame.
*/
public MainWindow()
{
setTitle("MyQQ\u670D\u52A1\u5668\u540E\u53F0\u7BA1\u7406");
Dimension size=Toolkit.getDefaultToolkit().getScreenSize();
setBounds((size.width-753)/2, (size.height-500)/2, 753, 530);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
serverMana=new ServerMana();
tabbedPane.addTab("服务管理", new ImageIcon(MainWindow.class.getResource("/client/img/manager_server.png")), serverMana, null);
userMana=new UserMana();
tabbedPane.addTab("用户管理", new ImageIcon(MainWindow.class.getResource("/client/img/manager_users.png")), userMana, null);
msgMana=new MsgMana();
tabbedPane.addTab("消息管理", new ImageIcon(MainWindow.class.getResource("/client/img/manager_message.png")), msgMana, null);
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE, 735, Short.MAX_VALUE)
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE, 492, Short.MAX_VALUE)
.addContainerGap())
);
contentPane.setLayout(gl_contentPane);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
int n=JOptionPane.showConfirmDialog(null,"确认退出吗?","确认对话框",
JOptionPane.YES_NO_OPTION );
if(n==JOptionPane.YES_OPTION)
System.exit(0);
}});
validate();
}
}
================================================
FILE: src/server/frame/MsgActionListener.java
================================================
package server.frame;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;
import javax.swing.JOptionPane;
import server.common.PageService;
import server.dao.MsgDao;
import server.entity.Msg;
public class MsgActionListener implements ActionListener
{
static PageService pageService;
MsgDao msgDao;
MsgMana msgMana;
public MsgActionListener(MsgMana msgMana)
{
msgDao = new MsgDao();
String sql = "select * from msg";
List list = msgDao.selectMsgs(sql);
pageService = new PageService(list);
this.msgMana = msgMana;
}
public void actionPerformed(ActionEvent e)
{
String strBtn = e.getActionCommand();
if ("删除".equals(strBtn))
{
int row = msgMana.table.getSelectedRow();
if (row != -1)
{
int msgId = Integer.parseInt(msgMana.table.getValueAt(row, 0).toString());
try {
if (msgDao.deleteMsg(msgId))
{
JOptionPane.showMessageDialog(null, "删除成功!");
}
else
{
JOptionPane.showMessageDialog(null, "删除失败!");
}
} catch (HeadlessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
pageService = new PageService(msgMana.refresh());
}
}
else if ("刷新".equals(strBtn))
{
msgMana.refresh();
}
else
{
List listPerPage = null;
if ("首页".equals(strBtn))
{
listPerPage = pageService.gotoFirst();
}
else if ("下一页".equals(strBtn))
{
listPerPage = pageService.gotoNext();
}
else if ("上一页".equals(strBtn))
{
listPerPage = pageService.gotoPre();
}
else if ("尾页".equals(strBtn))
{
listPerPage = pageService.gotoLast();
}
int rowCount = msgMana.model.getRowCount();// 获取表格中共有几行
for (int i = 0; i < rowCount; i++)
{
msgMana.model.removeRow(0);
}
msgMana.lblCurrent.setText("当前在第"
+ (pageService.getCurrentPage() + 1) + "页");
for (int i = 0; i < listPerPage.size(); i++)
{
Msg msg = (Msg) listPerPage.get(i);
Object[] rowData = { msg.getMsgId(),
msg.getMsgContent(), msg.getSendFrom(), msg.getSendTo(),
msg.getSendTime(), msg.getRemark(), msg.getMsgTye()};
msgMana.model.addRow(rowData);
}
}
}
}
================================================
FILE: src/server/frame/MsgMana.java
================================================
package server.frame;
import java.util.List;
import java.util.Vector;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import server.common.PageService;
import server.dao.MsgDao;
import server.entity.Msg;
import javax.swing.LayoutStyle.ComponentPlacement;
public class MsgMana extends JPanel {
public JTable table;
public DefaultTableModel model;
private Vector columnNames = new Vector();
private JLabel lblNum;
public JLabel lblCurrent;
public MsgActionListener msgActionListener;
public MsgMana()
{
JScrollPane scrollPane = new JScrollPane();
columnNames.add("消息ID");
columnNames.add("消息内容");
columnNames.add("消息发送者ID");
columnNames.add("消息接收者ID");
columnNames.add("消息发送时间");
columnNames.add("消息备注");
columnNames.add("消息类型");
model = new DefaultTableModel(columnNames, 0);
table = new JTable(model)
{
Boolean[] canEdit = new Boolean[] { false, true, true, true, true,
true, true };
@Override
public boolean isCellEditable(int row, int column)
{
// TODO Auto-generated method stub
return canEdit[column];
}
};
scrollPane.setViewportView(table);
lblNum = new JLabel("\u51710\u9875 /");
lblCurrent = new JLabel("\u5F53\u524D\u5728\u7B2C1\u9875");
JButton btnFirst = new JButton("\u9996\u9875");
JButton btnPre = new JButton("\u4E0A\u4E00\u9875");
JButton btnNext = new JButton("\u4E0B\u4E00\u9875");
JButton btnLast = new JButton("\u5C3E\u9875");
JButton btnDelete = new JButton("\u5220\u9664");
JButton btnReresh = new JButton("\u5237\u65B0");
// 为每个按钮注册监听器
msgActionListener = new MsgActionListener(this);
btnFirst.addActionListener(msgActionListener);
btnPre.addActionListener(msgActionListener);
btnNext.addActionListener(msgActionListener);
btnLast.addActionListener(msgActionListener);
btnDelete.addActionListener(msgActionListener);
btnReresh.addActionListener(msgActionListener);
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(40)
.addComponent(btnFirst, GroupLayout.PREFERRED_SIZE, 69, GroupLayout.PREFERRED_SIZE)
.addGap(4)
.addComponent(btnPre)
.addGap(10)
.addComponent(btnNext, GroupLayout.PREFERRED_SIZE, 75, GroupLayout.PREFERRED_SIZE)
.addGap(25)
.addComponent(btnLast, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE)
.addGap(82)
.addComponent(btnDelete, GroupLayout.PREFERRED_SIZE, 75, GroupLayout.PREFERRED_SIZE)
.addGap(33)
.addComponent(btnReresh, GroupLayout.PREFERRED_SIZE, 69, GroupLayout.PREFERRED_SIZE)
.addContainerGap(65, Short.MAX_VALUE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(264)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblNum, GroupLayout.PREFERRED_SIZE, 51, GroupLayout.PREFERRED_SIZE)
.addGroup(groupLayout.createSequentialGroup()
.addGap(46)
.addComponent(lblCurrent, GroupLayout.PREFERRED_SIZE, 75, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(295, Short.MAX_VALUE))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 299, GroupLayout.PREFERRED_SIZE)
.addGap(29)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblNum)
.addComponent(lblCurrent))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(1)
.addComponent(btnFirst))
.addGroup(groupLayout.createSequentialGroup()
.addGap(1)
.addComponent(btnPre))
.addGroup(groupLayout.createSequentialGroup()
.addGap(1)
.addComponent(btnNext))
.addComponent(btnLast)
.addGroup(groupLayout.createSequentialGroup()
.addGap(1)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnReresh)
.addComponent(btnDelete))))
.addGap(22))
);
setLayout(groupLayout);
// 将数据添加到表格中
refresh();
}
public List refresh()
{// 先移出表格监听器
// 得到总行数
int sumRow = model.getRowCount();
// 清空表格
for (int i = 0; i < sumRow; i++)
{
model.removeRow(0);
}
MsgDao msgDao = new MsgDao();
String sql = "select * from msg";
List list = msgDao.selectMsgs(sql);
PageService service = new PageService(list);
List listTemp = service.gotoFirst();
lblNum.setText("共" + service.getTotalPage() + "页/");
lblCurrent.setText("当前在第" + (service.getCurrentPage() + 1) + "页");
for (int i = 0; i < listTemp.size(); i++)
{
Msg msg = (Msg) listTemp.get(i);
Object[] rowData = new Object[] { msg.getMsgId(),
msg.getMsgContent(), msg.getSendFrom(), msg.getSendTo(),
msg.getSendTime(), msg.getRemark(), msg.getMsgTye() };
model.addRow(rowData);
}
return list;
}
}
================================================
FILE: src/server/frame/ServerActionListen.java
================================================
package server.frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import com.MyTools;
import server.QQServer;
public class ServerActionListen implements ActionListener{
QQServer qqServer=null;
ServerMana serverMana=null;
public ServerActionListen(ServerMana serverMana)
{
this.serverMana=serverMana;
}
public void actionPerformed(ActionEvent e)
{
String cmd=e.getActionCommand();
if(cmd.equals("启动MyQQ服务器"))
{
qqServer=new QQServer(MyTools.QQServerPort);
serverMana.allTime=0;
serverMana.startTime=System.currentTimeMillis();
serverMana.isRun=true;
serverMana.lblState.setText("服务器正在运行中...");
this.serverMana.btnStart.setActionCommand("停止MyQQ服务器");
}
else if(cmd.equals("停止MyQQ服务器"))
{
if(qqServer!=null)
{
qqServer.closeServer();
serverMana.isRun=false;
serverMana.lblState.setText("服务器已关闭。");
JOptionPane.showMessageDialog(null,"本次服务器总共运行"+serverMana.allTime+"秒");
this.serverMana.btnStart.setActionCommand("启动MyQQ服务器");
}
}
}
}
================================================
FILE: src/server/frame/ServerMana.java
================================================
package server.frame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import server.QQServer;
import client.frame.MyPanel;
import com.MyTools;
import java.util.Calendar;
import java.awt.Font;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTextArea;
import javax.swing.LayoutStyle.ComponentPlacement;
public class ServerMana extends JPanel implements Runnable
{
QQServer qqServer=null;//QQ服务器
JButton btnStart;
JLabel lblTime;
Calendar calendar=Calendar.getInstance();
private JLabel currentTime;
private JLabel label_1;
private JLabel lblRun;
private JLabel lblStateShow;
public JLabel lblState;
public int allTime=0;
public long startTime=0;
public long endTime=0;
public boolean isRun=false;
public JTextArea textArea公告;
private JPanel panel;
private JTextArea textArea弹窗;
private JButton btn弹窗;
public ServerMana()
{
setLayout(null);
btnStart = new JButton("\u542F\u52A8MyQQ\u670D\u52A1\u5668");
btnStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
startOrCloseServer();
}
});
btnStart.setFont(new Font("微软雅黑", Font.BOLD, 28));
btnStart.setBounds(29, 30, 301, 76);
add(btnStart);
JLabel label = new JLabel("\u5F53\u524D\u670D\u52A1\u5668\u65F6\u95F4\uFF1A");
label.setBounds(29, 169, 106, 15);
add(label);
currentTime = new JLabel("");
currentTime.setBounds(153, 169, 192, 15);
add(currentTime);
label_1 = new JLabel("\u670D\u52A1\u5668\u8FD0\u884C\u65F6\u95F4\uFF1A");
label_1.setBounds(29, 203, 106, 15);
add(label_1);
lblRun = new JLabel("");
lblRun.setBounds(153, 203, 135, 15);
add(lblRun);
lblStateShow = new JLabel("\u5F53\u524D\u670D\u52A1\u5668\u72B6\u6001\uFF1A");
lblStateShow.setBounds(28, 132, 107, 15);
add(lblStateShow);
lblState = new JLabel("服务器未运行");
lblState.setBounds(153, 132, 135, 15);
add(lblState);
JPanel panel公告 = new JPanel();
panel公告.setBorder(new TitledBorder(null, "\u53D1\u5E03\u804A\u5929\u5BA4\u516C\u544A", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(59, 59, 59)));
panel公告.setBounds(29, 231, 289, 240);
add(panel公告);
textArea公告 = new JTextArea();
JButton btn发布公告 = new JButton("\u53D1\u5E03\u804A\u5929\u5BA4\u516C\u544A");
btn发布公告.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
sendPublicMessage();
}
});
GroupLayout gl_panel公告 = new GroupLayout(panel公告);
gl_panel公告.setHorizontalGroup(
gl_panel公告.createParallelGroup(Alignment.LEADING)
.addComponent(textArea公告, GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)
.addGroup(Alignment.TRAILING, gl_panel公告.createSequentialGroup()
.addContainerGap(63, Short.MAX_VALUE)
.addComponent(btn发布公告, GroupLayout.PREFERRED_SIZE, 142, GroupLayout.PREFERRED_SIZE)
.addGap(56))
);
gl_panel公告.setVerticalGroup(
gl_panel公告.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_panel公告.createSequentialGroup()
.addComponent(textArea公告, GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btn发布公告, GroupLayout.PREFERRED_SIZE, 47, GroupLayout.PREFERRED_SIZE))
);
panel公告.setLayout(gl_panel公告);
panel = new JPanel();
panel.setBorder(new TitledBorder(null, "\u53D1\u5E03\u5F39\u7A97\u516C\u544A", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.setBounds(330, 231, 256, 240);
add(panel);
panel.setLayout(null);
textArea弹窗 = new JTextArea();
textArea弹窗.setBounds(16, 33, 222, 139);
panel.add(textArea弹窗);
btn弹窗 = new JButton("\u53D1\u5E03\u5F39\u7A97\u516C\u544A");
btn弹窗.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
showWindow();
}
});
btn弹窗.setBounds(71, 177, 127, 46);
panel.add(btn弹窗);
Thread thread=new Thread(this);
thread.start();
}
//设置窗体的背景图片
/*@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);//这句话有时候必须写,有时候可以不写
g.drawImage(MyTools.getIcon("../img/registerBGimg2.jpg").getImage(), 0, 0, null);
}*/
public void run()
{
while(true)
{
showTime();
if(isRun)
{
endTime=System.currentTimeMillis();
showRunTime();
}
else
{
showRunTime();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void showTime()
{
Calendar calendar=Calendar.getInstance();
String time=calendar.get(Calendar.YEAR)+"年"
+(calendar.get(Calendar.MONTH)+1)+"月"
+calendar.get(Calendar.DATE)+"日"
+" "
+calendar.get(Calendar.HOUR_OF_DAY)+":"
+calendar.get(Calendar.MINUTE)+":"
+calendar.get(Calendar.SECOND);
currentTime.setText(time);
}
public void showRunTime()
{
allTime=(int)(endTime-startTime)/1000;
lblRun.setText(String.valueOf(allTime));
}
public void startOrCloseServer()
{
if(btnStart.getText().equals("启动MyQQ服务器"))
{
qqServer=new QQServer(MyTools.QQServerPort);
allTime=0;
startTime=System.currentTimeMillis();
isRun=true;
lblState.setText("服务器正在运行中...");
btnStart.setText("停止MyQQ服务器");
}
else if(btnStart.getText().equals("停止MyQQ服务器"))
{
if(qqServer!=null)
{
qqServer.closeServer();
isRun=false;
lblState.setText("服务器已关闭。");
JOptionPane.showMessageDialog(null,"本次服务器总共运行"+allTime+"秒");
btnStart.setText("启动MyQQ服务器");
}
}
}
/**
* 发布聊天室公告
*/
public void sendPublicMessage()
{
if(btnStart.getText().equals("停止MyQQ服务器"))
{
if(textArea公告.getText().equals(""))
JOptionPane.showMessageDialog(null, "公告内容不能为空!");
else
qqServer.sendPublicMessage(textArea公告.getText());
}
else
{
JOptionPane.showMessageDialog(null, "您还未启动MyQQ服务器,不能发布公告!");
}
}
/**
* 弹窗
*/
public void showWindow()
{
if(btnStart.getText().equals("停止MyQQ服务器"))
{
if(textArea弹窗.getText().equals(""))
JOptionPane.showMessageDialog(null, "弹窗内容不能为空!");
else
qqServer.sendShowWindow(textArea弹窗.getText());
}
else
{
JOptionPane.showMessageDialog(null, "您还未启动MyQQ服务器,不能发布弹窗公告!");
}
}
}
================================================
FILE: src/server/frame/UserActionListen.java
================================================
package server.frame;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;
import javax.swing.JOptionPane;
import server.common.PageService;
import server.dao.UserDao;
import server.entity.Users;
public class UserActionListen implements ActionListener
{
static PageService pageService;
UserDao userDao;
UserMana userMana;
public UserActionListen(UserMana userMana)
{
userDao = new UserDao();
List list = userDao.queryAll();
pageService = new PageService(list);
this.userMana = userMana;
}
public void actionPerformed(ActionEvent e)
{
String strBtn = e.getActionCommand();
if("删除".equals(strBtn))
{
int row=userMana.table.getSelectedRow();
if(row!=-1)
{
int userId=Integer.parseInt(userMana.table.getValueAt(row, 0).toString());
try {
if(userDao.delete(userId))
{
JOptionPane.showMessageDialog(null, "删除成功!");
}
else
{
JOptionPane.showMessageDialog(null, "删除失败!");
}
} catch (HeadlessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//userMana.refresh();
pageService = new PageService(userMana.refresh());
}
}
else if("刷新".equals(strBtn))
{
//userMana.refresh();
pageService = new PageService(userMana.refresh());
}
else if("查找一".equals(strBtn))
{
userMana.model.removeTableModelListener(userMana.userTableCahnged);
Users user=null;
int rowCount = userMana.model.getRowCount();
UserDao userDao=new UserDao();
if(userMana.txtId.equals(null)||userMana.txtId.equals(""))
{
JOptionPane.showMessageDialog(null, "请输入用户ID");
}
else
{
int userId=Integer.parseInt(userMana.txtId.getText());
user=userDao.queryById(userId);
if(user==null)
{
JOptionPane.showMessageDialog(null, "用户不存在!");
return;
}
for (int i = 0; i listPerPage = null;
if ("首页".equals(strBtn))
{
listPerPage = pageService.gotoFirst();
}
else if ("下一页".equals(strBtn))
{
listPerPage = pageService.gotoNext();
}
else if ("上一页".equals(strBtn))
{
listPerPage = pageService.gotoPre();
}
else if ("尾页".equals(strBtn))
{
listPerPage = pageService.gotoLast();
}
int rowCount = userMana.model.getRowCount();// 获取表格中共有几行
for (int i = 0; i < rowCount; i++)
{
userMana.model.removeRow(0);
}
userMana.lblCurrent.setText("当前在第" + (pageService.getCurrentPage()+1) + "页");
for (int i = 0; i < listPerPage.size(); i++)
{
Users user = (Users) listPerPage.get(i);
Object[] rowData =
{ user.getId(), user.getName(), user.getPwd(),user.getIp(),user.getState(),user.getGender(), user.getEmail(),
user.getLastLogin(),user.getLastExit(), user.getBirthday()};
userMana.model.addRow(rowData);
}
userMana.model.addTableModelListener(userMana.userTableCahnged);
}
}
}
================================================
FILE: src/server/frame/UserMana.java
================================================
package server.frame;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import server.common.PageService;
import server.dao.UserDao;
import server.entity.Users;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
public class UserMana extends JPanel {
JScrollPane scrollpane = new JScrollPane();
Vector columnNames = new Vector();
public DefaultTableModel model;
public JTable table;
public JLabel lblNum;
public JLabel lblCurrent;
public UserTableCahnged userTableCahnged;
JButton btnFirst = new JButton("首页");
JButton btnNext = new JButton("下一页");
JButton btnPre = new JButton("上一页");
JButton btnLast = new JButton("尾页");
JButton btnDelete = new JButton("\u5220\u9664");
private final JButton btnUpdate = new JButton("\u5237\u65B0");
public JTextField txtId;
public JTextField txtName;
public UserMana()
{
columnNames.add("用户ID");
columnNames.add("用户名");
columnNames.add("密码");
columnNames.add("IP");
columnNames.add("状态");
columnNames.add("性别");
columnNames.add("Email");
columnNames.add("最近上线时间");
columnNames.add("最后下线时间");
columnNames.add("生日");
model = new DefaultTableModel(columnNames, 0);
table = new JTable(model)
{
boolean[] canEdit = new boolean[] { false, true, true, false, true,
true, true, false, false, true };
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return canEdit[columnIndex];
}
};
table.getAutoscrolls();
scrollpane.setViewportView(table);
UserActionListen userActionListen=new UserActionListen(this);
userTableCahnged=new UserTableCahnged(table);
model.addTableModelListener(userTableCahnged);
btnFirst.addActionListener(userActionListen);
btnPre.addActionListener(userActionListen);
btnNext.addActionListener(userActionListen);
btnLast.addActionListener(userActionListen);
lblNum=new JLabel();
lblCurrent=new JLabel();
btnDelete.addActionListener(userActionListen);
btnUpdate.addActionListener(userActionListen);
JLabel lblid = new JLabel("\u6309\u7528\u6237ID\u67E5\u627E\uFF1A");
txtId = new JTextField();
txtId.setColumns(10);
JLabel label = new JLabel("\u6309\u7528\u6237\u540D\u67E5\u627E\uFF1A");
txtName = new JTextField();
txtName.setColumns(10);
JButton btnSearch1 = new JButton("\u67E5\u627E\u4E00");
JButton btnSeach2 = new JButton("\u67E5\u627E\u4E8C");
btnSearch1.addActionListener(userActionListen);
btnSeach2.addActionListener(userActionListen);
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(24)
.addComponent(lblid)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(txtId, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED, 100, Short.MAX_VALUE)
.addComponent(label)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(txtName, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
.addGap(200))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(scrollpane, GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE))
.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
.addContainerGap(240, Short.MAX_VALUE)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(37)
.addComponent(lblCurrent, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE))
.addComponent(lblNum, GroupLayout.PREFERRED_SIZE, 43, GroupLayout.PREFERRED_SIZE))
.addGap(291))
.addGroup(groupLayout.createSequentialGroup()
.addGap(53)
.addComponent(btnFirst)
.addGap(5)
.addComponent(btnPre)
.addGap(5)
.addComponent(btnNext)
.addGap(5)
.addComponent(btnLast)
.addGap(85)
.addComponent(btnDelete)
.addGap(18)
.addComponent(btnUpdate)
.addContainerGap(99, Short.MAX_VALUE))
.addGroup(groupLayout.createSequentialGroup()
.addGap(165)
.addComponent(btnSearch1)
.addPreferredGap(ComponentPlacement.RELATED, 187, Short.MAX_VALUE)
.addComponent(btnSeach2, GroupLayout.PREFERRED_SIZE, 71, GroupLayout.PREFERRED_SIZE)
.addGap(154))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(35)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblid)
.addComponent(txtId, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(label)
.addComponent(txtName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGap(18)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnSearch1)
.addComponent(btnSeach2))
.addGap(16)
.addComponent(scrollpane, GroupLayout.PREFERRED_SIZE, 223, GroupLayout.PREFERRED_SIZE)
.addGap(31)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblCurrent)
.addComponent(lblNum))
.addGap(18)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(btnFirst)
.addComponent(btnPre)
.addComponent(btnNext)
.addComponent(btnLast)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnUpdate)
.addComponent(btnDelete)))
.addGap(73))
);
setLayout(groupLayout);
refresh();
}
public List refresh()
{
model.removeTableModelListener(userTableCahnged);
int rowCount = model.getRowCount(); // 将表格清空
for (int i = 0; i < rowCount; i++)
model.removeRow(0);
UserDao userDao=new UserDao();
List list=userDao.queryAll();
PageService pageService=new PageService(list);
List listTemp=pageService.gotoFirst();
lblNum.setText("共"+pageService.getTotalPage()+"页/");
lblCurrent.setText("当前在第"+(pageService.getCurrentPage()+1)+"页");
for (Users user : listTemp)
{
Object[] rowData =
{ user.getId(), user.getName(), user.getPwd(),user.getIp(),user.getState(),user.getGender(), user.getEmail(),
user.getLastLogin(),user.getLastExit(), user.getBirthday()};
model.addRow(rowData);
}
model.addTableModelListener(userTableCahnged);
return list;
}
}
================================================
FILE: src/server/frame/UserTableCahnged.java
================================================
package server.frame;
import java.awt.HeadlessException;
import java.sql.Date;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import server.dao.UserDao;
import server.entity.Users;
public class UserTableCahnged implements TableModelListener {
JTable table;
public UserTableCahnged(JTable table)
{
this.table=table;
}
public void tableChanged(TableModelEvent e) {
int row=e.getFirstRow();
int userId=Integer.parseInt(table.getValueAt(row, 0).toString());
String userName=table.getValueAt(row, 1).toString();
String pwdString=table.getValueAt(row, 2).toString();
//String IP=table.getValueAt(row, 3).toString();
//String state=table.getValueAt(row, 4).toString();
String userGender=table.getValueAt(row, 5).toString();
String userEmail=table.getValueAt(row, 6).toString();
//String userSignature=table.getValueAt(row, 5).toString();
Date userBirthday=Date.valueOf(table.getValueAt(row, 9).toString());
Users user=new Users(userId,userName,pwdString, userGender, userEmail,userBirthday);
UserDao userDao=new UserDao();
try {
if(userDao.update(user))
{
JOptionPane.showMessageDialog(null, "修改成功!");
}
else {
JOptionPane.showMessageDialog(null, "修改失败!");
}
} catch (HeadlessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}