编写一数据报通信程序,实现简单的聊天功能。
“聊天内容”和“输入文本”分别为当前聊天的历史信息和当前要传送出去的聊天文本。“确定”、“清空”、“退出”三个按钮分别实现发送当前聊天文本、清空当前聊天文本和退出系统的功能。import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Frame extends JFrame implements WindowListener{
private JTextArea text;
private JTextField ipText;
private JTextField sendText;
private JButton button;
private JButton button1;
private JButton button2;
private DatagramSocket socket;
private JScrollBar vsBar;
public Frame(){
setTitle("聊天器");
setBounds(100, 150,481, 371);
text=new JTextArea();
text.setEditable(true);
setLayout(null);
JScrollPane textPanel = new JScrollPane(text);
vsBar = textPanel.getVerticalScrollBar();
textPanel.setBounds(10,10, 320, 240);
getContentPane().add(textPanel);
JLabel label=new JLabel("请输入对方IP:");
label.setFont(new Font("",Font.BOLD,14));
label.setBounds(342, 24, 110, 24);
getContentPane().add(label);
ipText = new JTextField();
ipText.setBounds(352, 54, 111, 31);
getContentPane().add(ipText);
button=new JButton();
button.setText("确定");
button.setBounds(363, 135, 85, 47);
button.setFont(new Font("",Font.BOLD,23));
getContentPane().add(button);
button.addActionListener(new send());
button1=new JButton("清空");
button1.setBounds(363, 200, 85, 47);
button1.setFont(new Font("",Font.BOLD,23));
getContentPane().add(button1);
button1.addActionListener(new clear());
button2=new JButton("退出");
button2.setBounds(363, 260, 85, 47);
button2.setFont(new Font("",Font.BOLD,23));
getContentPane().add(button2);
button2.addActionListener(new exit());
this.addWindowListener(this);
sendText = new JTextField();
sendText.setBounds(10, 260, 320, 47);
getContentPane().add(sendText);
//server();
pack();
setVisible(true);
}
class send implements ActionListener{
public void actionPerformed(ActionEvent e) {
try{
String ip=ipText.getText();
InetAddress address=InetAddress.getByName(ip);
byte[] data=sendText.getText().getBytes();
DatagramP