import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
public class Chat extends Frame {
JLabel da=new JLabel("聊天程序");
Label a=new Label("聊天记录:");
Label b=new Label("用户名称::");
Label c=new Label("对方IP:");
Label d=new Label("发送消息");
TextField mingcheng=new TextField() ;
TextField ip=new TextField();
TextField data=new TextField();
JButton fs=new JButton("发送");
List lst=new List();
JButton qb=new JButton("清屏") ;
DatagramSocket ds= null;
Font zt=new Font("TimesRoman",Font.BOLD,40);
Font gy=new Font("TimesRoman",Font.BOLD,15);
public Chat() {
try{
ds=new DatagramSocket(3000);
}catch(Exception e){
e.printStackTrace();
}
this.setLayout(null);
this.add(mingcheng);
this.add(ip);
this.add(da);
this.add(data);
this.add(fs);
this.add(lst);
this.add(qb);
this.add(a);
this.add(b);
this.add(c);
this.add(d);
this.setBackground(new Color(200,200,0));
fs.setMnemonic(java.awt.event.KeyEvent.VK_ENTER);
qb.setMnemonic('p');
da.setFont(zt);
da.setBounds(215,40,170,50);
a.setFont(gy);
a.setBounds(20,100,140,25);
mingcheng.setFont(gy);
mingcheng.setBounds(420,130,150,30);
b.setFont(gy);
b.setBounds(420,100,140,25);
c.setFont(gy);
c.setBounds(420,180,150,30);
lst.setFont(gy);
lst.setBounds(20,130,380,250);
d.setFont(gy);
d.setBounds(20,390,150,30);
qb.setFont(gy);
qb.setBounds(300,390,100,30);
ip.setFont(gy);
ip.setBounds(420,220,150,30);
data.setFont(gy);
data.setBounds(20,430,470,50);
fs.setFont(gy);
fs.setBounds(500,430,70,50);
mingcheng.requestFocus();
lst.setFocusable(false);
new Thread(new Runnable(){
public synchronized void run(){
byte buf[]=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,1024);
while(true){
try{
ds.receive(dp);
lst.add("$"+dp.getAddress().getHostAddress()+"$ "+new String(buf,0,dp.getLength())+"\n",0);
}catch(Exception e){
if(!ds.isClosed()){
e.printStackTrace();
}
}
}
}
}).start();
fs.addActionListener(new ActionListener(){
public synchronized void actionPerformed(ActionEvent e){
if(!ip.getText().trim().equals("")){
byte [] buf;
buf=(mingcheng.getText()+":\n "+data.getText()).getBytes();
try{
DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName(ip.getText()),3000);
ds.send(dp);
lst.add(mingcheng.getText()+":\n "+data.getText()+"\n",0);
}catch(Exception es){
es.printStackTrace();
}
}else{
lst.add("请输入对方IP\n",0);
}
data.setText("");
data.requestFocus();
}
});
qb.addActionListener(new ActionListener(){
public synchronized void actionPerformed(ActionEvent e){
lst.removeAll();
data.requestFocus();
}
});
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
ds.close();
dispose();
System.exit(0);
}
});
}
public static void main(String[] args){
Chat m=new Chat();
m.setVisible(true);
m.setTitle("Chat");
m.setSize(600, 500);
m.setResizable(false);
}
}
评论1
最新资源