java带图形用户的聊天_速求用JAVA语言写聊天室的源代码。 提示:使用Swing图形用户界面、多线程、网络编程等技术。...

满意答案

02ae427d08e371d7e90d5b995e828d6d.png

断點1999

2013.11.10

02ae427d08e371d7e90d5b995e828d6d.png

采纳率:44%    等级:13

已帮助:8562人

还不是很完善的

import javax.swing.JFrame;

import javax.swing.JTextArea;

import javax.swing.JLabel;

import javax.swing.JTextField;

import javax.swing.JButton;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import java.net.InetAddress;

import java.net.DatagramSocket;

import java.net.DatagramPacket;

public class ChatRoom{

public static void main(String []args){

JFrame f=new JFrame();

f.setSize(700,600);

f.setTitle("聊天室");

f.setLayout(null);

//创建文本域:

final JTextArea textshow=new JTextArea();

textshow.setBounds(0,0,700,300);

textshow.setEditable(false);//不可编辑

f.add(textshow);

//创建标签1;

JLabel lab1=new JLabel();

lab1.setBounds(100,320,80,20);

lab1.setText("IP地址:");

f.add(lab1);

//ip地址文本框:

final JTextField text=new JTextField();

text.setBounds(190,320,100,20);

text.setText("127.0.0.1");

f.add(text);

//标签2:

JLabel lab2=new JLabel();

lab2.setBounds(310,320,80,20);

lab2.setText("端口号:");

f.add(lab2);

//端口 文本框

final JTextField textport=new JTextField();

textport.setBounds(400,320,100,20);

textport.setText("8888");

textport.setEditable(false);

f.add(textport);

//输入文本域:

final JTextArea textsend=new JTextArea();

textsend.setBounds(0,360,700,160);

f.add(textsend);

//发送按钮:

JButton btn1=new JButton();

btn1.setText("发送信息");

btn1.setBounds(590,530,100,30);

f.add(btn1);

btn1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

String userIp=text.getText();

String userPort=textport.getText();

String usertext=textsend.getText();

try

{

InetAddress add=InetAddress.getByName(userIp);

int port=new Integer(userPort);

byte []bs=usertext.getBytes();

DatagramPacket dp=new DatagramPacket(bs,bs.length,add,port);

DatagramSocket ds=new DatagramSocket();

ds.send(dp);

textsend.setText("");

textsend.requestFocus();

}

catch (Exception ex)

{

}

}

});

new Thread(){

public void run(){

try

{

DatagramSocket ds=new DatagramSocket(8888);

while (true)

{

byte []bs=new byte[1024];

DatagramPacket dp=new DatagramPacket(bs,1024);

ds.receive(dp);

String str=new String(bs);

str=str.trim();

if (textshow.getText().equals(""))

{

textshow.setText(str);

continue;

}

textshow.setText(textshow.getText()+"\r\n"+str);

}

}

catch (Exception ex)

{

}

}

}.start();

f.setLocationRelativeTo(null);

f.setVisible(true);

}

}

22分享举报

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值