GUI部分由Jformdesigner自动生成
网络编程部分由UDP实现
效果图如下:
代码实现:
public class Chat extends Frame
{
public Chat() {
initComponents();
initOthers();
}
private void initOthers() {
this.setVisible(true);
sendArea.setLineWrap(true); //激活自动换行功能
sendArea.setWrapStyleWord(true); // 激活断行不断字功能
new Receive().start();
try {
socket = new DatagramSocket();
bw = new BufferedWriter(new FileWriter("config.txt",true)); //需要在尾部追加
} catch (Exception e) {
e.printStackTrace();
}
}
private DatagramSocket socket ;
private BufferedWriter bw;
private void thisWindowClosing(WindowEvent e) {
socket.close();
try {
bw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
private void clearMouseClicked(MouseEvent e) {
displayArea.setText("");
}
private void shakeMouseClicked(MouseEvent e){
try {
send(new byte[]{-1},sendArea.getText());
} catch (Exception e1) {
e1.printStackTrace();
}
}
private void send(byte[] arr, String ip) throws Exception{
DatagramPacket packet =
new DatagramPacket(arr, arr.length, InetAddress.getByName(ip), 9999);
socket.send(packet); //发送数据
}
private void shake()
{
int x = this.getLocation().x; //获取横坐标位置
int y = this.getLocation().y; //获取纵坐标位置
for(int i = 0; i < 20; i++) {
try {
this.setLocation(x + 20, y + 20);
Thread.sleep(20);
this.setLocation(x + 20, y - 2