package MyChatRoom;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public class MyChatRoom
{
public static void main(String Args [])
{
logFrame log=new logFrame();
}
}
//聊天模块
class MyFrame extends JFrame implements ActionListener
{
public MyFrame(int a,String ip)
{
//获取传来的参数
ipA=ip;
selectNum=a;
//基本设置
setTitle("Sun聊天小工具");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//创建3个面板,一个放文本框,一个放按钮,一个放图片
JPanel textpanel = new JPanel();
JPanel buttonPanel=new JPanel();
JPanel picPanel=new JPanel();
Container contentPane = getContentPane();
GridBagConstraints cc=new GridBagConstraints();
GridBagLayout ca=new GridBagLayout();
contentPane.setLayout(ca);
cc.fill=GridBagConstraints.BOTH;
//初始化一个容器
cc.gridwidth=1;
cc.gridheight=2;
contentPane.add(picPanel);
ca.setConstraints(picPanel,cc);
cc.weighty=0.0;
cc.gridwidth=GridBagConstraints.REMAINDER;
cc.gridheight=1;
cc.weighty=1.0;
contentPane.add(textpanel);
ca.setConstraints(textpanel,cc);
contentPane.add(buttonPanel);
ca.setConstraints(buttonPanel,cc);
//网格式布局
GridBagConstraints c=new GridBagConstraints();
GridBagLayout gridbag=new GridBagLayout();
textpanel.setLayout(gridbag);
c.fill=GridBagConstraints.BOTH;
//初始化组件
//发送按钮
btSet=new JButton("发送");
buttonPanel.add(btSet);
btSet.addActionListener(this);
//取消按钮
btCancel=new JButton("取消");
buttonPanel.add(btCancel);
btCancel.addActionListener(this);
//清空按钮
btClear=new JButton("清屏");
buttonPanel.add(btClear);
btClear.addActionListener(this);
//显示消息框
c.weightx=1.0;
c.weighty=1.0;
c.gridwidth=GridBagConstraints.REMAINDER;
getBox=new JTextArea(15,30);
getBox.setEditable(false);
myScro=new JScrollPane(getBox);
textpanel.add(myScro);
gridbag.setConstraints(myScro,c);
//设置文本框显示数据往下翻页
getBox.setCaretPosition(getBox.getText().length());
//标签项
c.weightx=1.0;
c.gridwidth=GridBagConstraints.RELATIVE;;
label1=new JLabel("输入");
label4=new JLabel("聊天内容");
c.gridwidth=GridBagConstraints.REMAINDER;
gridbag.setConstraints(label4,c);
textpanel.add(label1);
textpanel.add(label4);
//发送消息框
setBox=new JTextArea(7,30);
myScro2=new JScrollPane(setBox);
textpanel.add(myScro2);
gridbag.setConstraints(myScro2,c);
//菜单项
//主菜单
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
gyMenu =new JMenu("关于(G)");
bzMenu =new JMenu("帮助(H)");
editMenu =new JMenu("编辑(E)");
szMenu =new JMenu("设置(S)");
menuBar.add(editMenu);
menuBar.add(gyMenu);
menuBar.add(bzMenu);
menuBar.add(szMenu);
//子菜单
aa =new JMenuItem("版权");
zzxx =new JMenuItem("作者信息");
gyMenu.add(aa);
gyMenu.add(zzxx);
aa.addActionListener(this);
zzxx.addActionListener(this);
cop=new JMenuItem("复制");
cut =new JMenuItem("剪切");
pas =new JMenuItem("粘贴");
editMenu.add(cop);
editMenu.add(cut);
editMenu.add(pas);
cop.addActionListener(this);
cut.addActionListener(this);
pas.addActionListener(this);
syzn=new JMenuItem("使用指南");
bzMenu.add(syzn);
syzn.addActionListener(this);
pifu=new JMenuItem("字体颜色");
beijing=new JMenuItem("背景色");
touxiang=new JMenuItem("更换头像");
szMenu.add(pifu);
szMenu.add(beijing);
szMenu.add(touxiang);
pifu.addActionListener(this);
beijing.addActionListener(this);
touxiang.addActionListener(this);
//匿名内部类实现监听
setBox.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
//当按回车时发送所输入的信息
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
sendString=setBox.getText();
out.println(sendString);
getBox.setCaretPosition(getBox.getText().length());
getBox.append("I Said:"+sendString+"\r\n");
setBox.setText("");
setBox.setCaretPosition(0);
}
}
});
imgLabel1=new JLabel(new ImageIcon("./MyChatRoom/bb.jpg"));
picPanel.add(imgLabel1);
imgLabel2=new JLabel(new ImageIcon("./MyChatRoom/aa.jpg"));
picPanel.add(imgLabel2);
picPanel.setLayout(new GridLayout(2,1));
//显示窗口
setVisible(true);
//选择作为客户端还是服务器端
switch(selectNum)
{
case 0:
serverRole();
break;
case 1:
clientRole();
break;
}
//启动线程处理输入流
thread=new MyThread(connectSocket,getBox);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
//包装输出流
try
{
out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(connectSocket.getOutputStream())),true);
}
catch(IOException e)
{
e.printStackTrace();
}
}
final int WIDTH=550;
final int HEIGHT=600;
JLabel label1,label4,imgLabel1,imgLabel2;
JButton btSet,btCancel,btClear;
JTextArea setBox,getBox;
JMenu gyMenu,bzMenu,editMenu,szMenu;
JMenuItem aa,cop,cut,pas,zzxx,syzn,pifu,beijing,touxiang;
JScrollPane myScro,myScro2;
String sendString;
MyThread thread=null;
ServerSocket serverSocket=null;;
Socket connectSocket=null;;
String ipA;
PrintWriter out=null;;
int selectNum;
String imgPath;
//作为服务器端的处理
public void serverRole()
{
try
{
serverSocket=new ServerSocket(5500);
getBox.append("正在等待对话请求\n");
connectSocket=serverSocket.accept();
getBox.setText("连接来自"+connectSocket.getInetAddress().toString()+"\n");
}
catch(Exception e)
{
getBox.append("对不起,由于某些原因,不能创建服务器\n");
btSet.setEnabled(false);
}
}
//作为客户端的处理
public void clientRole()
{
try
{
connectSocket=new Socket(ipA,5500);
getBox.setText("成功连接至"+ipA+"\n");
}
catch(Exception e)
{
getBox.append("对不起,无法连接!\r\n请重新登录并输入正确的IP地址");
btSet.setEnabled(false);
}
}
//按钮监听
public void actionPerformed(ActionEvent e)
{
Object o=e.getSource();
//发送按钮处理
if(o==btSet)
{
sendString=setBox.getText();
out.println(sendString);
getBox.setCaretPosition(getBox.getText().length());
getBox.append("I Said:"+sendString+"\r\n");
setBox.setText("");
setBox.setCaretPosition(setBox.getText().length());
}
//取消按钮处理
if(o==btCancel)
{
setBox.setText("");
}
//清空按钮处理
if(o==btClear)
{
getBox.setText("");
}
//复制处理
if(o==cop)
{
getBox.copy();
}
//剪切处理
if(o==cut)
{
getBox.cut();
}
//粘贴处理
if(o==pas)
{
setBox.paste();
}
if(o==zzxx)
{
JOptionPane.showMessageDialog(this,"作者:沈光辉,学号:20095392");
}
if(o==aa)
{
JOptionPane.showMessageDialog(this,"版权所有,盗版必究!");
}
if(o==syzn)
{
JOptionPane.showMessageDialog(this,"请等待消息框显示连接信息后再进行通信");
}
//打开调色板设置背景色
if(o==pifu)
{
Color color=JColorChooser.showDialog(this, "调色板", this.getBackground());
if(color!=null)
getBox.setForeground(color);
setBox.setForeground(color);
}
if(o==beijing)
{
Color color=JColorChooser.showDialog(this, "调色板", this.getBackground());
if(color!=null)
getBox.setBackground(color);
setBox.setBackground(color);
}
//更改头像
if(o==touxiang)
{
JFileChooser chooser=new JFileChooser("F:/文件/本学期相关课件/Java高级应用代码/MyChatRoomProgram/MyChatRoom");
//设置过滤条件
FileNameExtensionFilter filter=new FileNameExtensionFilter("图片文件——jpg","jpg");
//获取当前文件目录
File file=chooser.getCurrentDirectory();
//设置当前文件目录
chooser.setCurrentDirectory(file);
//设置过滤器
chooser.setFileFilter(filter);
int i=chooser.showDialog(this,"选择");
if(i==JFileChooser.APPROVE_OPTION)
{
imgPath=chooser.getSelectedFile().getAbsolutePath();
//创建ImageIcon对象
ImageIcon img=new ImageIcon(imgPath);
//创建Image对象,ImageIcon的getImage()方法返回该类型对象
Image sourceImg=img.getImage();
//该方法用来缩放图像、
Image scaleImg=sourceImg.getScaledInstance(200,250,Image.SCALE_DEFAULT);
//setIcon(Icon icon)
imgLabel1.setIcon(new ImageIcon(scaleImg));
}
}
}
}
//线程类1,用来处理输入流数据显示
class MyThread extends Thread
{
BufferedReader in=null;
String inStr=null;
JTextArea getBox;
//用构造方法传入socket和文本域以作相应的处理
public MyThread(Socket soc,JTextArea a)
{
getBox=a;
try
{
in =new BufferedReader(new InputStreamReader(soc.getInputStream()));
}
catch(IOException e)
{
e.printStackTrace();
}
}
//run方法
public void run()
{
try
{
while(true)
{
inStr=in.readLine();
getBox.setCaretPosition(getBox.getText().length());
getBox.append("He said:"+inStr+"\r\n");
Thread.sleep(500);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
//登录验证模块
class logFrame extends JFrame implements ActionListener
{
//构造方法
public logFrame()
{
//主面板
setTitle("用户登录");
setSize(400,270);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cotn=getContentPane();
//添加面板
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
JPanel panel3=new JPanel();
JPanel panel4=new JPanel();
JPanel panel5=new JPanel();
JPanel panel6=new JPanel();
cotn.add(panel6);
cotn.add(panel1);
cotn.add(panel2);
cotn.add(panel4);
cotn.add(panel3);
cotn.add(panel5);
//网格式布局
cotn.setLayout(new GridLayout(6,1));
//添加组件
user=new JLabel("用 户 名");
pass=new JLabel("密 码");
ipLabel=new JLabel("I P 地址");
userName=new JTextField(20);
passWord=new JPasswordField(20);
ipAdd=new JTextField("localhost",20);
ipAdd.setEditable(false);
panel1.add(user);
panel1.add(userName);
panel2.add(pass);
panel2.add(passWord);
panel3.add(ipLabel);
panel3.add(ipAdd);
headLabel=new JLabel("用户登录");
panel6.add(headLabel);
//选择作为服务器端还是客户端
serverR=new JRadioButton("服务器端",true);
clientR=new JRadioButton("客户端",false);
myGroup=new ButtonGroup();
myGroup.add(serverR);
myGroup.add(clientR);
panel4.add(serverR);
panel4.add(clientR);
serverR.addActionListener(this);
clientR.addActionListener(this);
serverR.addKeyListener(new logListener());
clientR.addKeyListener(new logListener());
//登录按钮
btOk=new JButton("登录");
btCanc=new JButton("退出");
panel5.add(btOk);
panel5.add(btCanc);
btOk.addActionListener(this);
btCanc.addActionListener(this);
btOk.addKeyListener(new logListener());
btCanc.addKeyListener(new logListener());
//菜单项
JMenuBar mainMenu=new JMenuBar();
setJMenuBar(mainMenu);
bz=new JMenu("帮助");
gy=new JMenu("关于");
mainMenu.add(gy);
mainMenu.add(bz);
bb=new JMenuItem("版本");
gy.add(bb);
bb.addActionListener(this);
gySun=new JMenuItem("关于Sun");
gy.add(gySun);
gySun.addActionListener(this);
syxz=new JMenuItem("使用指南");
bz.add(syxz);
syxz.addActionListener(this);
//为组件添加键盘事件监听
userName.addKeyListener(new logListener());
passWord.addKeyListener(new logListener());
ipAdd.addKeyListener(new logListener());
//显示窗口。最后才显示,防止面板有些元素不能正常显示。
setVisible(true);
}
JMenu bz,gy;
JMenuItem bb,gySun,syxz;
JTextField userName,ipAdd;
JPasswordField passWord;
JLabel user,pass,ipLabel,headLabel;
ButtonGroup myGroup;
JRadioButton serverR,clientR;
JButton btOk,btCanc;
//num选择的角色
public int num;
String ipAddress;
//内部类实现监听
class logListener extends KeyAdapter
{
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
//键盘确定选择是客户端
if(e.getSource()==clientR)
{
clientR.setSelected(true);
ipAdd.setEditable(true);
ipAdd.setCaretPosition(ipAdd.getText().length());
num=1;
}
//键盘确定选择是服务器端
else if(e.getSource()==serverR)
{
serverR.setSelected(true);
ipAdd.setEditable(false);
num=0;
}
//键盘确定选择是退出按钮
else if(e.getSource()==btCanc)
{
System.exit(0);
}
//键盘确定选择的是其他组件,则默认进行登录验证
else
logTest();
}
}
}
//登录验证方法
public void logTest()
{
String s1=userName.getText().trim();
String s2=passWord.getText().trim();
String s3=ipAdd.getText().trim();
if(s1.equals("20095392"))
{
headLabel.setText("正在连接...");
ipAddress=ipAdd.getText().trim();
//创建线程,启动聊天窗口
logThread ca=new logThread(num,ipAddress);
//启动
ca.start();
//释放登录窗口资源
logFrame.this.dispose();
}
else
{
JOptionPane.showMessageDialog(this,"用户名不存在或密码错误!");
passWord.setText("");
}
}
//按钮事件实现
public void actionPerformed(ActionEvent e)
{
Object o=e.getSource();
//选择的是服务器端
if(o==serverR)
{
num=0;
ipAdd.setEditable(false);
}
//选择的是客户端
if(o==clientR)
{
num=1;
ipAdd.setEditable(true);
ipAdd.setCaretPosition(ipAdd.getText().length());
ipAdd.requestFocus(true);
}
//登录验证
if(o==btOk)
{
logTest();
}
//取消登录,退出系统
if(o==btCanc)
{
System.exit(0);
}
if(o==syxz)
{
JOptionPane.showMessageDialog(this,"请先选择本客户端的角色(服务器端或客户端)\r\n若选择客户端请输入所要连接的服务器端IP地址");
}
if(o==bb)
{
JOptionPane.showMessageDialog(this,"Version-1.0");
}
if(o==gySun)
{
JOptionPane.showMessageDialog(this,"作者-沈光辉 学号-20095392");
}
}
}
//线程类2,用来启动聊天窗口模块
class logThread extends Thread
{
int num=0;
String ipA;
//run方法
public logThread(int n,String ip)
{
num=n;
ipA=ip;
}
public void run()
{
try
{
{
MyFrame a=new MyFrame(num,ipA);
Thread.sleep(1000);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}