設置發送快捷鍵(按回車鍵發送消息)


package UDP;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Demo01_GUI extends JFrame {
public static void main(String[] args) {
gui1 = new Demo01_GUI();
gui1.southPanel();
gui1.centerPanel();
gui1.init();
gui1.event();
}

private JPanel south;
private JButton log;
private JTextField tf; // 存ip
private JButton send;
private JButton clear;
private JButton shake;
private JPanel center;
private TextArea viewText;
private TextArea sendText;
private DatagramSocket socket1;
private DatagramSocket socket;
private static Demo01_GUI gui1;
private BufferedWriter bw;

public Demo01_GUI() {
super("即時通訊");

}

/**
* 初始化窗體JFrame
*/
public void init() {
this.setSize(400, 600);// 設置窗體的大小
Point point = new Point(800, 300);// 設置顯示坐標
this.setLocation(point);// 設置窗體的位置
this.setVisible(true);// 顯示出設置好的窗體
try {
bw = new BufferedWriter(new FileWriter("config.txt", true));// 初始化的時候就要創建出這個寫入文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Receive().start();// 啟動接收消息線程

}

/**
* 創建Frame窗體中南邊的JPanel
*/
public void southPanel() {
south = new JPanel();// 創建南邊的JPanel
tf = new JTextField(8);// 創建文本字段,存儲IP地址
tf.setText("127.0.0.1");// 給文本框設置默認的IP地址
send = new JButton("發送");// 創建第一個發送按鈕
log = new JButton("記錄");// 創建第一個記錄按鈕
clear = new JButton("清除");// 創建第一個清屏按鈕
shake = new JButton("震動");// 創建第一個震動按鈕
// 先要把創建好的這些按鈕和文本字段放到這個Panel里面
south.add(tf);
south.add(send);
south.add(log);
south.add(clear);
south.add(shake);
// 然后再把這個Panel添加到Frame框的南邊(下邊)
this.add(south, BorderLayout.SOUTH);
}

/**
* 創建Frame窗體中中間的JPanel
*/
public void centerPanel() {
center = new JPanel(); // 創建中間的JPanel
// 中間的panel需要兩個Textarea
viewText = new TextArea(); // 顯示文本的區域
sendText = new TextArea(4, 1); // 發送文本的區域
center.setLayout(new BorderLayout());// 將JPanel設置為邊界布局管理器
// 設置完Panel為邊界布局管理器之后,就可以吧viewText和sendText分別設置到中間和南邊
center.add(sendText, BorderLayout.SOUTH);// 將發送文本區域設置到南邊
center.add(viewText, BorderLayout.CENTER);// 將顯示文本區域設置到中間
viewText.setEditable(false);// 將顯示文本區域設置為不可編輯
viewText.setBackground(Color.WHITE);// 將顯示文本區域背景顏色設置為白色
viewText.setFont(new Font("xxx", Font.PLAIN, 15));// 設置輸入字體大小
sendText.setFont(new Font("xxx", Font.PLAIN, 15));// 設置顯示區域字體大小
this.add(center, BorderLayout.CENTER);// 然后再把這個JPanel添加到JFrame框的中間
}

/**
* 設置關閉窗體按鈕
*/
public void event() {
// 這個是表示在窗口添加一個Windows事件消息,目的是我們關閉窗口的時候可以正常的退出
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
try {
socket1.close();// 點擊關閉窗體之前停止接收線程
bw.close();// 關閉這個流
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.exit(0);
}
});
send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
send();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

});
log.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
logFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

/**
* 獲取聊天記錄
*/
private void logFile() throws IOException {
// TODO Auto-generated method stub
bw.flush();// 刷新緩沖區
FileInputStream fis = new FileInputStream("config.txt");// 讀取這個文件
ByteArrayOutputStream baos = new ByteArrayOutputStream();// 在內存中創建緩沖區
int len;
byte[] arr = new byte[8192];
while ((len = fis.read(arr)) != -1) {
baos.write(arr, 0, len); // 將讀取到的內容寫入緩沖區
}
String str = baos.toString();// 將緩沖區中的內容轉換成字符串
viewText.setText(str);
fis.close();
}
});
/**
* 清屏功能
*/
clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
viewText.setText("");
}
});
/**
* 觸發屏幕震動功能
*/
shake.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
send(new byte[] { -1 }, tf.getText());// 調用給指定ip發送消息這個方法
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
/**
* 監聽點擊鍵盤回車鍵發送消息
*/
sendText.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
send();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});

}

/**
* 屏幕震動功能
*/
private void shake() {
int x = this.getLocation().x;// 獲取橫坐標位置
int y = this.getLocation().y;// 獲取縱坐標位置
for (int i = 0; i < 10; i++) { // 循環改變窗體的位置
try {
this.setLocation(x + 20, y + 20);
Thread.sleep(20);
this.setLocation(x + 20, y - 20);
Thread.sleep(20);
this.setLocation(x - 20, y + 20);
Thread.sleep(20);
this.setLocation(x - 20, y - 20);
Thread.sleep(20);
this.setLocation(x, y);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

/**
* 接收和發送需要同時進行,所以定義成多線程的
*
* @author lenovo 接收消息
*/
private class Receive extends Thread {

public void run() {
try {
socket1 = new DatagramSocket(9996);
DatagramPacket packet = new DatagramPacket(new byte[8192], 8192);
while (true) {
socket1.receive(packet);// 接收信息
byte[] arr = packet.getData(); // 獲取字節數據
int len = packet.getLength();// 獲取有效的字節數據
if (arr[0] == -1 && len == 1) {// 如果發過來的數組第一個存儲的值是-1,並且數組長度是1
shake();
continue;
}
String message = new String(arr, 0, len);// 將接收到的有效字節轉換成字符串
String time = getCurrentTime();// 獲取當前時間
String ip = packet.getAddress().getHostAddress();// 獲取ip地址
String str = time + " " + ip + "對我說:\r\n\r\n" + message + "\r\n\r\n";
bw.write(str);// 將接收的消息寫入數據庫
viewText.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 給指定ip發送消息
*
* @param arr
* @param ip
* @throws IOException
*/
private void send(byte[] arr, String ip) throws IOException {
DatagramPacket packet = new DatagramPacket(arr, arr.length, InetAddress.getByName(ip), 9996);
socket.send(packet);// 發送數據
}

/**
* 發送消息
*
* @throws IOException
*/
private void send() throws IOException {
// TODO Auto-generated method stub
String message = sendText.getText(); // 獲取發送區域的內容
String ip = tf.getText(); // 獲取ip地址
ip = ip.trim().length() == 0 ? "255.255.255.255" : ip;
socket = new DatagramSocket();
send(message.getBytes(), ip);// 調用send方法給指定ip發送消息
String time = getCurrentTime(); // 拿到當前時間
String str = time + "我對:" + (ip.equals("255.255.255.255") ? "所有人" : ip) + "說 \r\n\r\n" + message + "\r\n\r\n"; // alt+shift+L 抽取局部變量
viewText.append(str); // 將發送的信息添加到顯示區域中
bw.write(str); // 將發送的消息寫入數據庫中
sendText.setText("");// 清空發送區域

}

/**
* 獲取到當前系統時間
*
* @return
*/
private String getCurrentTime() {
Date date = new Date(); // 創建當前日期對象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");// 格式化
return sdf.format(date); // 返回格式化后的時間
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM