java 大一课程设计 qq聊天程序socket=new Socket();
textPanel.send.setEnabled(false);
thread=new Thread(this);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==save)
{
savefile.setVisible(true);
if(savefile.getFile()!=null)
{
try{
File file=new File(savefile.getDirectory(),savefile.getFile());
FileWriter tofile=new FileWriter(file);
BufferedWriter out=new BufferedWriter(tofile);
out.write(textPanel.getWholeText(), 0, textPanel.getWholeText().length());
out.close();
tofile.close();
}
catch(IOException e2){}
}
}
else if(e.getSource()==doodle)
{
thePaint.setVisible(true);
}
else if(e.getSource()==Disconnect)
{
if(socket.isConnected())
{
try{
ps.writeUTF("QUIT:");
ps.flush();
socket.close();}catch(IOException ee){System.out.println("无法关闭");}
}
setTitle("用户"+name+"离线");
textPanel.send.setEnabled(false);
nameList.removeAll();
nameLable.setText("在线用户: "+"人数: "+(nameList.getItemCount()));
}
else if(e.getSource()==connect)
{
try//请求和服务器建立套接字连接
{
if(socket.isConnected()){}
else
{
InetAddress address=InetAddress.getLocalHost();
InetSocketAddress socketAddress=new InetSocketAddress(address,8080);
socket.connect(socketAddress);
reader=new DataInputStream(socket.getInputStream());
ps=new DataOutputStream(socket.getOutputStream());
out=new ObjectOutputStream(socket.getOutputStream());
in=new ObjectInputStream(socket.getInputStream());
ps.writeUTF(name);//开始即传输用户名
ps.flush();
setTitle("用户"+name+"在线");
thread.start();
}
}catch(IOException ee){}
}
else if(e.getSource()==groupChat)
{
groupMode=true;
condition.setText("群 聊\n");
textPanel.send.setEnabled(true);
}
else if(e.getSource()==privateChat)
{
groupMode=false;
condition.setText("私 聊\n");
textPanel.send.setEnabled(true);
}
else if(e.getSource()==nameList)
{
if(!groupMode)
{
indexName=nameList.getSelectedItem();
condition.setText("私 聊\n与"+nameList.getSelectedItem()+"聊天中\n");
}
}
else if(e.getSource()==textPanel.send)
{
if(e.getSource()==textPanel.send)
{
textPanel.text=textPanel.in.getText();
Font f=textPanel.in.getFont();
textPanel.out.setFont(f);
Color c=textPanel.in.getForeground();
textPanel.out.setForeground(c);
textPanel.in.setText("");
if(!groupMode)
{
textPanel.out.append("\n"+"我说:"+textPanel.text+"\n");
}
else
{
textPanel.out.append("\n");
}
System.out.println("文本输出~~");
String text=textPanel.text;
if(groupMode)
{
StringBuffer msg=new StringBuffer("MSG:");
msg.append(text);
String s=msg.toString();
try{
ps.writeUTF(s);
ps.flush();}catch(IOException ee){System.out.println("输出文本错误");}
System.out.println("成功输出");
}
else
{
StringBuffer msg=new StringBuffer("MSGTOONE:");
msg.append(indexName+":"+text);
String s=msg.toString();
try{
ps.writeUTF(s);
ps.flush();}catch(IOException ee){System.out.println("输出文本错误");}
System.out.println("成功输出");
}
}
1