Java 文件傳輸助手的實(shí)現(xiàn)(單機(jī)版)
項(xiàng)目介紹
用 Java 實(shí)現(xiàn)單機(jī)版的文件傳輸助手項(xiàng)目。
涉及技術(shù)知識(shí):
Swing 組件 I/O流 正則表達(dá)式 Java 事務(wù)處理機(jī)制基礎(chǔ)功能:
登錄、注冊(cè) 發(fā)送文字 發(fā)送圖片、文件 文字、圖片、文件的信息記錄 歷史記錄的保存、回顯及清空 信息發(fā)送的日期 退出高級(jí)功能:
發(fā)送表情包 查看和查找歷史記錄 點(diǎn)擊歷史記錄的文件圖片能直接打開(kāi) 拖拽輸入信息、圖片、文件功能總覽:
功能實(shí)現(xiàn)
一、登錄
進(jìn)入登錄界面
未輸入賬號(hào),登錄彈出提示
輸入賬號(hào),但未輸入密碼登錄時(shí)彈出提示
賬號(hào)或者密碼輸入錯(cuò)誤登錄時(shí)彈出提示
登錄成功時(shí)進(jìn)入主界面
登錄界面:
package frame;import java.awt.Color;import java.awt.Container;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPasswordField;import javax.swing.JTextField;import function.Login;/** * 文件傳輸助手登陸界面 * * @author:360°順滑 * * @date:2020/04/27 * */public class LoginFrame {public static JFrame loginJFrame;public static JLabel userNameLabel;public static JTextField userNameTextField;public static JLabel passwordLabel;public static JPasswordField passwordField;public static JButton loginButton;public static JButton registerButton;public static void main(String[] args) {// 創(chuàng)建窗體loginJFrame = new JFrame('文件傳輸助手');loginJFrame.setSize(500, 300);loginJFrame.setLocationRelativeTo(null);loginJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);ImageIcon image = new ImageIcon('src/pictures/logo.png');loginJFrame.setIconImage(image.getImage());loginJFrame.setResizable(false);// 創(chuàng)建內(nèi)容面板Container container = loginJFrame.getContentPane();container.setLayout(null);// 創(chuàng)建“賬號(hào)”標(biāo)簽userNameLabel = new JLabel('賬號(hào):');userNameLabel.setFont(new Font('行楷', Font.BOLD, 25));userNameLabel.setBounds(60, 25, 100, 100);container.add(userNameLabel);// 創(chuàng)建輸入賬號(hào)文本框userNameTextField = new JTextField();userNameTextField.setFont(new Font('黑體', Font.PLAIN, 23));userNameTextField.setBounds(133, 61, 280, 33);container.add(userNameTextField);// 創(chuàng)建“密碼”標(biāo)簽passwordLabel = new JLabel('密碼:');passwordLabel.setFont(new Font('行楷', Font.BOLD, 25));passwordLabel.setBounds(60, 90, 100, 100);container.add(passwordLabel);// 創(chuàng)建輸入密碼文本框passwordField = new JPasswordField();passwordField.setBounds(133, 127, 280, 33);passwordField.setFont(new Font('Arial', Font.BOLD, 23));container.add(passwordField);// 創(chuàng)建登錄按鈕loginButton = new JButton('登錄');loginButton.setBounds(170, 185, 70, 40);loginButton.setFont(new Font('微軟雅黑', 1, 18));loginButton.setBackground(Color.WHITE);loginButton.setFocusPainted(false);loginButton.setBorderPainted(false);container.add(loginButton);// 創(chuàng)建注冊(cè)按鈕registerButton = new JButton('注冊(cè)');registerButton.setBounds(282, 185, 70, 40);registerButton.setFont(new Font('微軟雅黑', 1, 18));registerButton.setBackground(Color.WHITE);registerButton.setFocusPainted(false);registerButton.setBorderPainted(false);container.add(registerButton);// 顯示窗體loginJFrame.setVisible(true);addListen();}// 為按鈕添加監(jiān)聽(tīng)器public static void addListen() {// 為登錄按鈕添加監(jiān)聽(tīng)事件loginButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub// 創(chuàng)建Login對(duì)象并把LoginFrame的文本框內(nèi)容作為參數(shù)傳過(guò)去Login login = new Login(userNameTextField, passwordField);// 判斷是否符合登錄成功的條件if (login.isEmptyUserName()) {emptyUserName(loginJFrame);} else {if (login.isEmptyPassword()) {emptyPasswordJDialog(loginJFrame);} else {if (login.queryInformation()) {loginJFrame.dispose();MainFrame mainFrame = new MainFrame(userNameTextField.getText());mainFrame.init();} else {failedLoginJDialog(loginJFrame);}}}}});// 為注冊(cè)按鈕添加監(jiān)聽(tīng)事件registerButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub// 隱藏當(dāng)前登錄窗口loginJFrame.setVisible(false);// 打開(kāi)注冊(cè)窗口new RegisterFrame().init();}});}/* * 由于各個(gè)標(biāo)簽長(zhǎng)度不同,所以為了界面美觀,就寫(xiě)了三個(gè)彈出對(duì)話框而不是一個(gè)! * */// 未輸入賬號(hào)時(shí)彈出提示對(duì)話框public static void emptyUserName(JFrame jFrame) {JDialog jDialog = new JDialog(jFrame, '提示');jDialog.setLayout(null);jDialog.setSize(300, 200);jDialog.setLocationRelativeTo(null);ImageIcon image = new ImageIcon('src/pictures/warn.png');jDialog.setIconImage(image.getImage());JLabel jLabel = new JLabel('未輸入賬號(hào)!');jLabel.setFont(new Font('行楷', 0, 21));jLabel.setBounds(82, 0, 200, 100);jDialog.add(jLabel);JButton button = new JButton('確定');button.setBounds(105, 80, 70, 40);button.setFont(new Font('微軟雅黑', 1, 18));button.setBackground(Color.WHITE);button.setFocusPainted(false);button.setBorderPainted(false);jDialog.add(button);button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubjDialog.dispose();}});jDialog.setVisible(true);}// 未輸入密碼時(shí)彈出提示對(duì)話框public static void emptyPasswordJDialog(JFrame jFrame) {JDialog jDialog = new JDialog(jFrame, '提示');jDialog.setLayout(null);jDialog.setSize(300, 200);jDialog.setLocationRelativeTo(null);ImageIcon image = new ImageIcon('src/pictures/warn.png');jDialog.setIconImage(image.getImage());JLabel jLabel = new JLabel('未輸入密碼!');jLabel.setFont(new Font('行楷', 0, 21));jLabel.setBounds(82, 0, 200, 100);jDialog.add(jLabel);JButton button = new JButton('確定');button.setBounds(105, 80, 70, 40);button.setFont(new Font('微軟雅黑', 1, 18));button.setBackground(Color.WHITE);button.setFocusPainted(false);button.setBorderPainted(false);jDialog.add(button);button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubjDialog.dispose();}});jDialog.setVisible(true);}// 賬號(hào)或密碼輸入錯(cuò)誤!public static void failedLoginJDialog(JFrame jFrame) {JDialog jDialog = new JDialog(jFrame, '提示');jDialog.setLayout(null);jDialog.setSize(300, 200);jDialog.setLocationRelativeTo(null);ImageIcon image = new ImageIcon('src/pictures/warn.png');jDialog.setIconImage(image.getImage());JLabel jLabel = new JLabel('賬號(hào)或密碼輸入錯(cuò)誤!');jLabel.setFont(new Font('行楷', 0, 20));jLabel.setBounds(47, 0, 200, 100);jDialog.add(jLabel);JButton button = new JButton('確定');button.setBounds(105, 80, 70, 40);button.setFont(new Font('微軟雅黑', 1, 18));button.setBackground(Color.WHITE);button.setFocusPainted(false);button.setBorderPainted(false);jDialog.add(button);button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubjDialog.dispose();}});jDialog.setVisible(true);}}
登錄判斷
package function;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.swing.JPasswordField;import javax.swing.JTextField;/** * 文件傳輸助手登錄功能 * * @author:360°順滑 * * @date: 2020/04/29 * */public class Login {JTextField userNameTextField;JPasswordField passwordField;public Login(JTextField userNameTextField, JPasswordField passwordField) {this.userNameTextField = userNameTextField;this.passwordField = passwordField;}//判斷賬號(hào)是否為空方法public boolean isEmptyUserName() {if (userNameTextField.getText().equals(''))return true;elsereturn false;}//判斷密碼是否為空方法public boolean isEmptyPassword() {//操作密碼框文本要先將其轉(zhuǎn)換為字符串if (''.equals(new String(passwordField.getPassword())))return true;elsereturn false;}// 查詢是否存在該賬號(hào)密碼public boolean queryInformation() {File file = new File('src/txt/userInformation.txt');FileReader fileReader = null;BufferedReader bufferedReader = null;boolean vis = false;try {fileReader = new FileReader(file);bufferedReader = new BufferedReader(fileReader);Pattern userNamePattern = Pattern.compile('用戶名:.+');Pattern passwordPattern = Pattern.compile('密碼:.+');String str1 = null;while ((str1 = bufferedReader.readLine()) != null) {Matcher userNameMatcher = userNamePattern.matcher(str1);if(userNameMatcher.find()) {if (('用戶名:' + userNameTextField.getText()).equals(userNameMatcher.group())) {String str2 = bufferedReader.readLine();Matcher passwordMatcher = passwordPattern.matcher(str2);if(passwordMatcher.find()) {if (('密碼:' + new String(passwordField.getPassword())).equals(passwordMatcher.group())) {vis = true;break;}}}}}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {bufferedReader.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {fileReader.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (vis)return true;elsereturn false;}}
主界面
package frame;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Dimension;import java.awt.Font;import java.awt.dnd.DnDConstants;import java.awt.dnd.DropTarget;import java.awt.dnd.DropTargetListener;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.Box;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JScrollPane;import javax.swing.JTextPane;import javax.swing.text.BadLocationException;import javax.swing.text.Document;import javax.swing.text.SimpleAttributeSet;import function.DropTargetFile;import function.FileSend;import function.RecordsEcho;import function.TextSend;/** * 文件傳輸助手主界面 * * @author 360°順滑 * * @date:2020/04/29 ~ 2020/04/30 * */public class MainFrame {String userName;public MainFrame() {};public MainFrame(String userName) {this.userName = userName;}private JButton fileButton;private JButton historicRecordsButton;private JButton sendButton;private JTextPane showPane;private JTextPane inputPane;private JButton expressionButton;private JScrollPane scrollShowPane;private Box buttonBox;private Box inputBox;private Box sendBox;private Box totalBox;private ImageIcon image;static JFrame mainFrame;public void init() {// 顯示文本窗格showPane = new JTextPane();showPane.setSize(600, 400);showPane.setBackground(Color.WHITE);showPane.setEditable(false);showPane.setBorder(null);showPane.setFont(new Font('宋體', 0, 25));// 顯示文本窗格添加滾動(dòng)條scrollShowPane = new JScrollPane(showPane);// 表情包按?并添加圖標(biāo)Icon expressionIcon = new ImageIcon('src/pictures/expression.png');expressionButton = new JButton(expressionIcon);expressionButton.setBackground(Color.WHITE);expressionButton.setFocusPainted(false);expressionButton.setBorderPainted(false);// 文件按鈕并添加圖標(biāo)Icon fileIcon = new ImageIcon('src/pictures/file.png');fileButton = new JButton(fileIcon);fileButton.setBackground(Color.WHITE);fileButton.setFocusPainted(false);fileButton.setBorderPainted(false);// 歷史記錄按鈕并添加圖標(biāo)Icon historicRecordsIcon = new ImageIcon('src/pictures/historicRecords.png');historicRecordsButton = new JButton(historicRecordsIcon);historicRecordsButton.setBackground(Color.WHITE);historicRecordsButton.setFocusPainted(false);historicRecordsButton.setBorderPainted(false);// 按鈕Box容器添加三個(gè)按鈕buttonBox = Box.createHorizontalBox();buttonBox.setPreferredSize(new Dimension(1000, 50));buttonBox.add(Box.createHorizontalStrut(10));buttonBox.add(expressionButton);buttonBox.add(Box.createHorizontalStrut(10));buttonBox.add(fileButton);buttonBox.add(Box.createHorizontalStrut(10));buttonBox.add(historicRecordsButton);// 添加 “歷史記錄”按鈕到右邊框的距離 到buttonBox容器中buttonBox.add(Box.createHorizontalGlue());// 輸入文本窗格inputPane = new JTextPane();inputPane.setSize(600, 300);inputPane.setFont(new Font('宋體', 0, 24));inputPane.setBackground(Color.WHITE);JScrollPane scrollInputPane = new JScrollPane(inputPane);// 輸入?yún)^(qū)域的Box容器inputBox = Box.createHorizontalBox();inputBox.setPreferredSize(new Dimension(1000, 150));inputBox.add(scrollInputPane);// 發(fā)送按鈕sendButton = new JButton('發(fā)送(S)');sendButton.setFont(new Font('行楷', Font.PLAIN, 20));sendButton.setBackground(Color.WHITE);sendButton.setFocusPainted(false);sendButton.setBorderPainted(false);// 發(fā)送Box容器并添加發(fā)送按鈕sendBox = Box.createHorizontalBox();sendBox.setPreferredSize(new Dimension(1000, 50));sendBox.setBackground(Color.white);sendBox.add(Box.createHorizontalStrut(710));sendBox.add(Box.createVerticalStrut(5));sendBox.add(sendButton);sendBox.add(Box.createVerticalStrut(5));// 總的Box容器添加以上3個(gè)BoxtotalBox = Box.createVerticalBox();totalBox.setPreferredSize(new Dimension(1000, 250));totalBox.setSize(1000, 400);totalBox.add(buttonBox);totalBox.add(inputBox);totalBox.add(Box.createVerticalStrut(3));totalBox.add(sendBox);totalBox.add(Box.createVerticalStrut(3));// 設(shè)置主窗體mainFrame = new JFrame('文件傳輸助手');mainFrame.setSize(950, 800);mainFrame.setLocationRelativeTo(null);mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 改變窗體logoimage = new ImageIcon('src/pictures/logo.png');mainFrame.setIconImage(image.getImage());mainFrame.setLayout(new BorderLayout());// 添加窗體以上兩個(gè)主要容器mainFrame.add(scrollShowPane, BorderLayout.CENTER);mainFrame.add(totalBox, BorderLayout.SOUTH);mainFrame.setVisible(true);// 添加監(jiān)聽(tīng)器addListen();// 信息記錄回顯到展示面板RecordsEcho echo = new RecordsEcho(userName, showPane);echo.read();}// 提示對(duì)話框public static void warnJDialog(String information) {JDialog jDialog = new JDialog(mainFrame, '提示');jDialog.setLayout(null);jDialog.setSize(300, 200);jDialog.setLocation(770, 400);ImageIcon image = new ImageIcon('src/pictures/warn.png');jDialog.setIconImage(image.getImage());JLabel jLabel = new JLabel(information);jLabel.setFont(new Font('微軟雅黑', 0, 18));jLabel.setBounds(65, 0, 200, 100);jDialog.add(jLabel);JButton button = new JButton('確定');button.setBounds(105, 80, 70, 40);button.setFont(new Font('微軟雅黑', 1, 18));button.setBackground(Color.WHITE);button.setFocusPainted(false);button.setBorderPainted(false);jDialog.add(button);// 為彈出對(duì)話框按鈕添加監(jiān)聽(tīng)事件button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubjDialog.dispose();}});jDialog.setVisible(true);}// 添加監(jiān)聽(tīng)事件@SuppressWarnings('unused')public void addListen() {/* * 為輸入文本添加目標(biāo)監(jiān)聽(tīng)器 */// 創(chuàng)建拖拽目標(biāo)監(jiān)聽(tīng)器DropTargetListener listener = new DropTargetFile(inputPane);// 在 inputPane上注冊(cè)拖拽目標(biāo)監(jiān)聽(tīng)器DropTarget dropTarget = new DropTarget(inputPane, DnDConstants.ACTION_COPY_OR_MOVE, listener, true);// 發(fā)送按鈕監(jiān)聽(tīng)事件sendButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {// TODO Auto-generated method stubTextSend textSend = new TextSend(showPane, inputPane, userName);textSend.sendText();}});// 輸入框添加鍵盤(pán)事件inputPane.addKeyListener(new KeyListener() {// 發(fā)生擊鍵事件時(shí)被觸發(fā)@Overridepublic void keyTyped(KeyEvent e) {}// 按鍵被釋放時(shí)被觸發(fā)@Overridepublic void keyReleased(KeyEvent e) {}// 按鍵被按下時(shí)被觸發(fā)@Overridepublic void keyPressed(KeyEvent e) {// TODO Auto-generated method stub// 如果按下的是 Ctrl + Enter 組合鍵 則換行if ((e.getKeyCode() == KeyEvent.VK_ENTER) && e.isControlDown()) {Document document = inputPane.getDocument();try {document.insertString(document.getLength(), 'n', new SimpleAttributeSet());} catch (BadLocationException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}// 否則發(fā)送} else if (e.getKeyCode() == KeyEvent.VK_ENTER) {TextSend textSend = new TextSend(showPane, inputPane, userName);textSend.sendText();}}});// 表情包按鈕監(jiān)聽(tīng)事件expressionButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubnew EmojiFrame(showPane, userName).init();}});// 文件按鈕監(jiān)聽(tīng)事件fileButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {// TODO Auto-generated method stubFileSend fileSend = new FileSend(userName, showPane, inputPane);fileSend.send();}});// 歷史記錄按鈕監(jiān)聽(tīng)事件historicRecordsButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubnew HistoricRecordsFrame(userName, showPane).init();}});}}
登錄之前如果沒(méi)有賬號(hào)就得先注冊(cè)一個(gè),那么進(jìn)入注冊(cè)功能!
二、注冊(cè)
點(diǎn)擊登錄界面的注冊(cè)按鈕,進(jìn)入注冊(cè)界面
未輸入賬號(hào)進(jìn)行注冊(cè)時(shí)
輸入賬號(hào)但未輸入密碼或者確認(rèn)密碼進(jìn)行注冊(cè)時(shí)
密碼和確認(rèn)密碼不一致時(shí)進(jìn)行注冊(cè)
賬號(hào)已存在進(jìn)行注冊(cè)時(shí)
注冊(cè)成功時(shí)
點(diǎn)擊確定按鈕或者關(guān)閉窗口后返回登錄界面
如果取消注冊(cè),直接點(diǎn)擊返回按鈕就可以返回登錄界面了
注冊(cè)界面
package frame;import java.awt.Color;import java.awt.Container;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPasswordField;import javax.swing.JTextField;import function.Register;/** * * 文件傳輸助手注冊(cè)界面 * * @author 360°順滑 * * @date: 2020/04/27 ~ 2020/04/28 * */public class RegisterFrame {public JFrame registerJFrame;public JLabel userNameLabel;public JTextField userNameTextField;public JLabel passwordLabel;public JPasswordField passwordField;public JLabel passwordAgainLabel;public JPasswordField passwordAgainField;public JButton goBackButton;public JButton registerButton;public void init() {// 創(chuàng)建窗體registerJFrame = new JFrame('文件傳輸助手');//registerJFrame.setTitle();registerJFrame.setSize(540, 400);registerJFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);ImageIcon image = new ImageIcon('src/pictures/logo.png');registerJFrame.setIconImage(image.getImage());registerJFrame.setLocationRelativeTo(null);registerJFrame.setResizable(false);// 創(chuàng)建內(nèi)容面板Container container = registerJFrame.getContentPane();container.setLayout(null);// 創(chuàng)建“賬號(hào)”標(biāo)簽userNameLabel = new JLabel('賬號(hào):');userNameLabel.setFont(new Font('行楷', Font.BOLD, 25));userNameLabel.setBounds(97, 25, 100, 100);container.add(userNameLabel);// 創(chuàng)建輸入賬號(hào)文本框userNameTextField = new JTextField();userNameTextField.setFont(new Font('黑體', Font.PLAIN, 23));userNameTextField.setBounds(170, 61, 280, 33);container.add(userNameTextField);// 創(chuàng)建“密碼”標(biāo)簽passwordLabel = new JLabel('密碼:');passwordLabel.setFont(new Font('行楷', Font.BOLD, 25));passwordLabel.setBounds(97, 90, 100, 100);container.add(passwordLabel);// 創(chuàng)建輸入密碼文本框passwordField = new JPasswordField();passwordField.setBounds(170, 125, 280, 33);passwordField.setFont(new Font('Arial', Font.BOLD, 23));container.add(passwordField);// 創(chuàng)建“確認(rèn)密碼”標(biāo)簽passwordAgainLabel = new JLabel('確認(rèn)密碼:');passwordAgainLabel.setFont(new Font('行楷', Font.BOLD, 25));passwordAgainLabel.setBounds(45, 150, 130, 100);container.add(passwordAgainLabel);// 創(chuàng)建確認(rèn)密碼文本框passwordAgainField = new JPasswordField();passwordAgainField.setBounds(170, 185, 280, 33);passwordAgainField.setFont(new Font('Arial', Font.BOLD, 23));container.add(passwordAgainField);// 創(chuàng)建返回按鈕goBackButton = new JButton('返回');goBackButton.setBounds(200, 260, 70, 40);goBackButton.setFont(new Font('微軟雅黑', 1, 18));goBackButton.setBackground(Color.WHITE);goBackButton.setFocusPainted(false);goBackButton.setBorderPainted(false);container.add(goBackButton);// 創(chuàng)建注冊(cè)按鈕registerButton = new JButton('注冊(cè)');registerButton.setBounds(330, 260, 70, 40);registerButton.setFont(new Font('微軟雅黑', 1, 18));registerButton.setBackground(Color.WHITE);registerButton.setFocusPainted(false);registerButton.setBorderPainted(false);container.add(registerButton);// 顯示窗體registerJFrame.setVisible(true);addListen();}// 為按鈕添加監(jiān)聽(tīng)事件public void addListen() {// 為注冊(cè)按鈕添加監(jiān)聽(tīng)事件registerButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub// 創(chuàng)建register對(duì)象,同時(shí)將RegisterFrame的文本框內(nèi)容作為參數(shù)傳過(guò)去Register register = new Register(userNameTextField, passwordField, passwordAgainField);// 判斷輸入賬號(hào)是否為空if (register.isEmptyUserName()) {emptyUserName(registerJFrame);} else {// 判斷輸入密碼是否為空if (register.isEmptyPassword()) {emptyPasswordJDialog(registerJFrame);}else {// 判斷密碼和確認(rèn)密碼是否一致if (register.isSamePassWord()) {// 判斷賬號(hào)是否已存在if (!register.isExistAccount()) {// 注冊(cè)成功!!!register.saveInformation();registerJFrame.dispose();userNameTextField.setText('');passwordField.setText('');passwordAgainField.setText('');new LoginFrame();LoginFrame.loginJFrame.setVisible(true);successRegisterJDialog(registerJFrame);} elseexistAccountJDialog(registerJFrame);} else {differentPasswordJDialog(registerJFrame);passwordField.setText('');passwordAgainField.setText('');}}}}});// 為返回按鈕添加監(jiān)聽(tīng)事件goBackButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// 銷毀注冊(cè)窗口registerJFrame.dispose();// 重新顯示登錄窗口new LoginFrame();LoginFrame.loginJFrame.setVisible(true);}});}/* * 由于各個(gè)標(biāo)簽長(zhǎng)度不同,所以為了界面美觀,就寫(xiě)了三個(gè)彈出對(duì)話框而不是一個(gè)! * */// 未輸入賬號(hào)時(shí)彈出提示對(duì)話框public void emptyUserName(JFrame jFrame) {JDialog jDialog = new JDialog(jFrame, '提示');jDialog.setLayout(null);jDialog.setSize(300, 200);jDialog.setLocationRelativeTo(null);ImageIcon image = new ImageIcon('src/pictures/warn.png');jDialog.setIconImage(image.getImage());JLabel jLabel = new JLabel('未輸入用戶名!');jLabel.setFont(new Font('行楷', 0, 21));jLabel.setBounds(73, 0, 200, 100);jDialog.add(jLabel);JButton button = new JButton('確定');button.setBounds(105, 80, 70, 40);button.setFont(new Font('微軟雅黑', 1, 18));button.setBackground(Color.WHITE);button.setFocusPainted(false);button.setBorderPainted(false);jDialog.add(button);button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubjDialog.dispose();}});jDialog.setVisible(true);}// 未輸入密碼時(shí)彈出提示對(duì)話框public void emptyPasswordJDialog(JFrame jFrame) {JDialog jDialog = new JDialog(jFrame, '提示');jDialog.setLayout(null);jDialog.setSize(300, 200);jDialog.setLocationRelativeTo(null);ImageIcon image = new ImageIcon('src/pictures/warn.png');jDialog.setIconImage(image.getImage());JLabel jLabel = new JLabel('未輸入密碼!');jLabel.setFont(new Font('行楷', 0, 21));jLabel.setBounds(73, 0, 200, 100);jDialog.add(jLabel);JButton button = new JButton('確定');button.setBounds(105, 80, 70, 40);button.setFont(new Font('微軟雅黑', 1, 18));button.setBackground(Color.WHITE);button.setFocusPainted(false);button.setBorderPainted(false);jDialog.add(button);button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubjDialog.dispose();}});jDialog.setVisible(true);}// 密碼和確認(rèn)密碼不一致時(shí)彈出提示框public void differentPasswordJDialog(JFrame jFrame) {JDialog jDialog = new JDialog(jFrame, '提示');jDialog.setLayout(null);jDialog.setSize(300, 200);jDialog.setLocationRelativeTo(null);ImageIcon image = new ImageIcon('src/pictures/warn.png');jDialog.setIconImage(image.getImage());JLabel jLabel = new JLabel('輸入密碼不一致!');jLabel.setFont(new Font('行楷', 0, 21));jLabel.setBounds(63, 0, 200, 100);jDialog.add(jLabel);JButton button = new JButton('確定');button.setBounds(105, 80, 70, 40);button.setFont(new Font('微軟雅黑', 1, 18));button.setBackground(Color.WHITE);button.setFocusPainted(false);button.setBorderPainted(false);jDialog.add(button);button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubjDialog.dispose();}});jDialog.setVisible(true);}// 已存在賬號(hào)彈出提示對(duì)話框public void existAccountJDialog(JFrame jFrame) {JDialog jDialog = new JDialog(jFrame, '提示');jDialog.setLayout(null);jDialog.setSize(300, 200);jDialog.setLocationRelativeTo(null);ImageIcon image = new ImageIcon('src/pictures/warn.png');jDialog.setIconImage(image.getImage());JLabel jLabel = new JLabel('該賬號(hào)已存在!');jLabel.setFont(new Font('行楷', 0, 21));jLabel.setBounds(73, 0, 200, 100);jDialog.add(jLabel);JButton button = new JButton('確定');button.setBounds(105, 80, 70, 40);button.setFont(new Font('微軟雅黑', 1, 18));button.setBackground(Color.WHITE);button.setFocusPainted(false);button.setBorderPainted(false);jDialog.add(button);button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubjDialog.dispose();}});jDialog.setVisible(true);}// 成功注冊(cè)對(duì)話框public void successRegisterJDialog(JFrame jFrame) {JDialog jDialog = new JDialog(jFrame, '提示');jDialog.setLayout(null);jDialog.setSize(300, 200);jDialog.setLocationRelativeTo(null);ImageIcon image = new ImageIcon('src/pictures/warn.png');jDialog.setIconImage(image.getImage());JLabel jLabel = new JLabel('注冊(cè)成功!');jLabel.setFont(new Font('行楷', 0, 21));jLabel.setBounds(73, 0, 200, 100);jDialog.add(jLabel);JButton button = new JButton('確定');button.setBounds(105, 80, 70, 40);button.setFont(new Font('微軟雅黑', 1, 18));button.setBackground(Color.WHITE);button.setFocusPainted(false);button.setBorderPainted(false);jDialog.add(button);button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub// 銷毀提示對(duì)話框jDialog.dispose();}});jDialog.setVisible(true);}}
注冊(cè)判斷
package function;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.swing.JPasswordField;import javax.swing.JTextField;/** * 文件傳輸助手注冊(cè)功能 * * @author:360°順滑 * * @date:2020/04/28 ~ 2020/04/29 * */public class Register {JTextField userNameTextField;JPasswordField passwordField;JPasswordField passwordAgainField;//將RegisterFrame參數(shù)傳入進(jìn)來(lái)public Register(JTextField userNameTextField, JPasswordField passwordField, JPasswordField passwordAgainField) {this.userNameTextField = userNameTextField;this.passwordField = passwordField;this.passwordAgainField = passwordAgainField;}//判斷賬號(hào)是否為空方法public boolean isEmptyUserName() {if (userNameTextField.getText().equals(''))return true;elsereturn false;}//判斷密碼是否為空方法public boolean isEmptyPassword() {//操作密碼框文本要先將其轉(zhuǎn)換為字符串if (''.equals(new String(passwordField.getPassword())) || ''.equals(new String(passwordAgainField.getPassword())))return true;elsereturn false;}//判斷密碼和輸入密碼是否一致方法public boolean isSamePassWord() {//操作密碼框文本要先將其轉(zhuǎn)換為字符串if (new String(passwordField.getPassword()).equals(new String(passwordAgainField.getPassword())))return true;elsereturn false;}//判斷賬號(hào)是否已存在方法public boolean isExistAccount() {File file = new File('src/txt/userInformation.txt');FileReader fileReader = null;BufferedReader bufferedReader = null;boolean vis = false;try {fileReader = new FileReader(file);bufferedReader = new BufferedReader(fileReader);//正則表達(dá)式Pattern pattern = Pattern.compile('用戶名:.+');String str = null;while ((str = bufferedReader.readLine()) != null) {Matcher matcher = pattern.matcher(str);if (matcher.find()) {if (('用戶名:' + userNameTextField.getText()).equals(matcher.group())) {vis = true;break;}}}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (bufferedReader != null) {try {bufferedReader.close();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}if (fileReader != null) {try {fileReader.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}if (!vis) {return false;} else {return true;}}//保存信息到本地public void saveInformation() {File file = new File('src/txt/userInformation.txt');FileWriter fileWriter = null;BufferedWriter bufferedWriter = null;try {fileWriter = new FileWriter(file, true);bufferedWriter = new BufferedWriter(fileWriter);bufferedWriter.write('用戶名:' + userNameTextField.getText());bufferedWriter.newLine();bufferedWriter.write('密碼:' + new String(passwordField.getPassword()));bufferedWriter.newLine();bufferedWriter.flush();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (bufferedWriter != null) {try {bufferedWriter.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (fileWriter != null) {try {fileWriter.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}
三、發(fā)送文字
輸入文字后可以點(diǎn)擊發(fā)送按鈕發(fā)送,也可以通過(guò)鍵盤(pán)Enter鍵發(fā)送
發(fā)送空白信息時(shí)彈出提示,提示框代碼在主界面類里
發(fā)送文本:
package function;import java.text.SimpleDateFormat;import java.util.Date;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.swing.JFrame;import javax.swing.JTextPane;import javax.swing.text.BadLocationException;import javax.swing.text.Document;import javax.swing.text.SimpleAttributeSet;import frame.MainFrame;/** * 實(shí)現(xiàn)發(fā)送消息,并保存到信息記錄 * * @author 360°順滑 * * @date 2020/05/01 * */public class TextSend {JFrame mainFrame;JTextPane textShowPane;JTextPane textInputPane;String userName;public TextSend(JTextPane textShowPane, JTextPane textInputPane, String userName) {this.textShowPane = textShowPane;this.textInputPane = textInputPane;this.userName = userName;}public void sendText() {if (!(''.equals(textInputPane.getText()))) {// 獲取日期并設(shè)置日期格式Date date = new Date();SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy-MM-dd hh:mm:ss');SimpleAttributeSet attributeSet = new SimpleAttributeSet();// 輸入文本String inputText = dateFormat.format(date) + 'n';Pattern pattern = Pattern.compile('.+[.].+');Matcher matcher = pattern.matcher(textInputPane.getText());// 判斷是否為文件boolean isFile = false;// 判斷是否為第一個(gè)文件boolean isFirst = true;while (matcher.find()) {isFile = true;// 獲得文件名int index = matcher.group().lastIndexOf('');String fileName = matcher.group().substring(index + 1);// 圖片的情況if (matcher.group().endsWith('.png') || matcher.group().endsWith('.jpg')|| matcher.group().endsWith('.jpeg') || matcher.group().endsWith('gif')) {Document document = textShowPane.getDocument();try {if (isFirst) {isFirst = false;document.insertString(document.getLength(), inputText, new SimpleAttributeSet());new RecordsEcho(userName, textShowPane).writeImage(matcher.group(), fileName);document.insertString(document.getLength(), 'n', new SimpleAttributeSet());}else {new RecordsEcho(userName, textShowPane).writeImage(matcher.group(), fileName);document.insertString(document.getLength(), 'n', new SimpleAttributeSet());}} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}} else {// 文件的情況Document document = textShowPane.getDocument();try {if (isFirst) {isFirst = false;document.insertString(document.getLength(), inputText, new SimpleAttributeSet());new RecordsEcho(userName, textShowPane).writeFile(matcher.group(), fileName);document.insertString(document.getLength(), 'n', new SimpleAttributeSet());}else {new RecordsEcho(userName, textShowPane).writeFile(matcher.group(), fileName);document.insertString(document.getLength(), 'n', new SimpleAttributeSet());}} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}if (!isFile) {// 實(shí)現(xiàn)發(fā)送文本太長(zhǎng)自動(dòng)換行String str = '';for (int i = 0; i < textInputPane.getText().length(); i++) {if (i != 0 && i % 15 == 0)str += 'n';str += textInputPane.getText().charAt(i);}Document document = textShowPane.getDocument();try {document.insertString(document.getLength(), inputText + str + 'nn', attributeSet);} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 把信息保存到對(duì)應(yīng)的用戶本地歷史記錄txt文件SaveRecords records = new SaveRecords(userName, inputText + textInputPane.getText() + 'nn');records.saveRecords();textInputPane.setText('');} else {new MainFrame();MainFrame.warnJDialog('不能發(fā)送空白信息!');}}}
其實(shí)這個(gè)類不單單只是發(fā)送文本這么簡(jiǎn)單,因?yàn)楹罄m(xù)實(shí)現(xiàn)了拖拽發(fā)送文件,拖拽后會(huì)在輸入框自動(dòng)輸入文件路徑,實(shí)現(xiàn)的代碼有關(guān)聯(lián),就寫(xiě)在這里了。
四、發(fā)送圖片 、文件和表情包
圖片文件的發(fā)送主要是通過(guò)打開(kāi)本地瀏覽發(fā)送的
發(fā)送文件、圖片、表情包:
package function;import java.awt.Color;import java.awt.Desktop;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFileChooser;import javax.swing.JTextPane;import javax.swing.text.BadLocationException;import javax.swing.text.Document;import javax.swing.text.SimpleAttributeSet;/** * 實(shí)現(xiàn)打開(kāi)文件按鈕發(fā)送圖片文件表情包 * * @author 360°順滑 * * @date 2020/05/01 */public class FileSend {String userName;String path;String fileName;JTextPane textShowPane;JTextPane textInputPane;public FileSend() {};public FileSend(String userName, JTextPane textShowPane, JTextPane textInputPane) {this.userName = userName;this.textShowPane = textShowPane;this.textInputPane = textInputPane;}// 彈出選擇框并判斷發(fā)送的是文件還是圖片public void send() {// 點(diǎn)擊文件按鈕可以打開(kāi)文件選擇框JFileChooser fileChooser = new JFileChooser();int result = fileChooser.showOpenDialog(null);if (result == JFileChooser.APPROVE_OPTION) {// 被選擇文件路徑path = fileChooser.getSelectedFile().getAbsolutePath();// 被選擇文件名稱fileName = fileChooser.getSelectedFile().getName();// 選擇的是圖片if (path.endsWith('.png') || path.endsWith('.jpg') || path.endsWith('.gif') || path.endsWith('.jpeg')) {sendImage(path, fileName);} else {sendFile(path, fileName);}}}// 發(fā)送圖片public void sendImage(String path, String fileName) {// 獲取圖片ImageIcon imageIcon = new ImageIcon(path);// 如果圖片比整個(gè)界面大則調(diào)整大小int width, height;if (imageIcon.getIconWidth() > 950 || imageIcon.getIconHeight() > 400) {width = 600;height = 250;} else {width = imageIcon.getIconWidth();height = imageIcon.getIconHeight();}// 設(shè)置圖片大小imageIcon.setImage(imageIcon.getImage().getScaledInstance(width, height, 0));// 獲取日期Date date = new Date();SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy-MM--dd HH:mm:ss');String input = dateFormat.format(date) + 'n';// 為圖片名稱添加按鈕,用于打開(kāi)圖片JButton button = new JButton(fileName);button.setFont(new Font('宋體', Font.PLAIN, 20));button.setBackground(Color.WHITE);button.setBorderPainted(false);button.setFocusPainted(false);// 獲取整個(gè)展示面板的內(nèi)容,方便圖片文件的插入Document document = textShowPane.getDocument();try {// 插入日期document.insertString(document.getLength(), input, new SimpleAttributeSet());// 插入圖片textShowPane.insertIcon(imageIcon);// 換行document.insertString(document.getLength(), 'n', new SimpleAttributeSet());// 插入按鈕,也就是圖片名稱textShowPane.insertComponent(button);document.insertString(document.getLength(), 'nn', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 為按鈕添加點(diǎn)擊事件button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubtry {// 實(shí)現(xiàn)打開(kāi)文件功能File file = new File(path);Desktop.getDesktop().open(file);} catch (IOException e2) {// TODO Auto-generated catch blocke2.printStackTrace();}}});// 輸入框重新清空textInputPane.setText('');// 保存路徑到對(duì)應(yīng)的賬號(hào)信息里String saveText = input + path + 'nn';SaveRecords records = new SaveRecords(userName, saveText);records.saveRecords();}// 發(fā)送文件public void sendFile(String path, String fileName) {// 獲取固定文件圖標(biāo)Icon fileImage = new ImageIcon('src/pictures/document.png');// 獲取日期Date date = new Date();SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss');String input = dateFormat.format(date) + 'n';// 為名稱添加按鈕JButton button = new JButton(fileName);button.setFont(new Font('宋體', Font.PLAIN, 20));button.setBackground(Color.WHITE);button.setBorderPainted(false);button.setFocusPainted(false);// 獲取面板內(nèi)容Document document = textShowPane.getDocument();try {document.insertString(document.getLength(), input, new SimpleAttributeSet());textShowPane.insertIcon(fileImage);textShowPane.insertComponent(button);document.insertString(document.getLength(), 'nn', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}//為名稱按鈕添加監(jiān)聽(tīng)事件,實(shí)現(xiàn)打開(kāi)功能button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubtry {// 實(shí)現(xiàn)打開(kāi)文件功能File file = new File(path);Desktop.getDesktop().open(file);} catch (IOException e2) {// TODO Auto-generated catch blocke2.printStackTrace();}}});textInputPane.setText('');// 保存路徑到對(duì)應(yīng)的賬號(hào)信息里String saveText = input + path + 'nn';SaveRecords records = new SaveRecords(userName, saveText);records.saveRecords();}//發(fā)送表情包功能public void sendEmoji(String path) {// 獲取圖片ImageIcon imageIcon = new ImageIcon(path);// 獲取日期Date date = new Date();SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy-MM--dd HH:mm:ss');String input = dateFormat.format(date) + 'n';// 獲取整個(gè)展示面板的內(nèi)容,方便圖片文件的插入Document document = textShowPane.getDocument();try {// 插入日期document.insertString(document.getLength(), input, new SimpleAttributeSet());// 插入圖片textShowPane.insertIcon(imageIcon);document.insertString(document.getLength(), 'nn', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 輸入框重新清空textInputPane.setText('');}}
五、保存歷史記錄
發(fā)送文字、圖片、文件和表情包的信息(文字或路徑)都要保存到本地,以便歷史信息的回顯,查找歷史信息。
package function;import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;/** * 該類實(shí)現(xiàn)保存信息記錄 * * * @author 360°順滑 * * @date 2020/05/01 * */public class SaveRecords {String userName;String input;public SaveRecords(String userName,String input) {this.userName = userName;this.input = input;}public void saveRecords() {String path = 'src/txt/' + userName + '.txt';File file = new File(path);// 文件不存在就創(chuàng)建一個(gè)if (!file.exists()) {try {file.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}FileWriter fileWriter = null;BufferedWriter bufferedWriter = null;try {fileWriter = new FileWriter(file,true);bufferedWriter = new BufferedWriter(fileWriter);bufferedWriter.write(input);bufferedWriter.flush();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (bufferedWriter != null) {try {bufferedWriter.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (fileWriter != null) {try {fileWriter.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}
六、歷史記錄回顯
登錄后進(jìn)入主界面或者進(jìn)入歷史記錄界面會(huì)看到該賬號(hào)以前發(fā)送過(guò)的信息記錄
歷史記錄回顯:
package function;import java.awt.Color;import java.awt.Desktop;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JTextPane;import javax.swing.text.BadLocationException;import javax.swing.text.Document;import javax.swing.text.SimpleAttributeSet;/** * * 該類實(shí)現(xiàn)歷史記錄回顯 * * @author 360°順滑 * * @date 2020/05/02 * */public class RecordsEcho {private String userName;private JTextPane showPane;public RecordsEcho(String userName, JTextPane showPane) {this.userName = userName;this.showPane = showPane;}// 將用戶的信息記錄回顯到展示面板public void read() {// 對(duì)應(yīng)賬號(hào)的信息記錄文本File file = new File('src/txt/' + userName + '.txt');// 文件不存在就創(chuàng)建一個(gè)if (!file.exists()) {try {file.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}FileReader fileReader = null;BufferedReader bufferedReader = null;try {fileReader = new FileReader(file);bufferedReader = new BufferedReader(fileReader);// 正則表達(dá)式Pattern pattern = Pattern.compile('.+[.].+');String str = null;while ((str = bufferedReader.readLine()) != null) {Matcher matcher = pattern.matcher(str);// 如果是文件或圖片if (matcher.find()) {// 獲得文件名int index = str.lastIndexOf('');String fileName = str.substring(index + 1);// 圖片的情況if (str.endsWith('.png') || str.endsWith('.jpg') || str.endsWith('.jpeg') || str.endsWith('gif')) {Pattern pattern1 = Pattern.compile('[emoji_].+[.].+');Matcher matcher1 = pattern1.matcher(fileName);// 如果是表情包if (matcher1.find()) {writeEmoji(str);} else {writeImage(str, fileName);}} else {// 文件的情況writeFile(str, fileName);}} else {// 如果是文本則直接寫(xiě)入writeText(str);}}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {bufferedReader.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {fileReader.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}// 把文本顯示在展示面板public void writeText(String str) {String s = '';for (int i = 0; i < str.length(); i++) {if (i != 0 && i % 30 == 0)s += 'n';s += str.charAt(i);}Document document = showPane.getDocument();try {document.insertString(document.getLength(), s + 'n', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void writeEmoji(String path) {// 獲取圖片ImageIcon imageIcon = new ImageIcon(path);// 獲取整個(gè)展示面板的內(nèi)容,方便圖片文件的插入Document document = showPane.getDocument();try {// 插入圖片showPane.insertIcon(imageIcon);// 換行document.insertString(document.getLength(), 'n', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 把圖片顯示在展示面板public void writeImage(String path, String fileName) {// 獲取圖片ImageIcon imageIcon = new ImageIcon(path);// 如果圖片比整個(gè)界面大則調(diào)整大小int width, height;if (imageIcon.getIconWidth() > 950 || imageIcon.getIconHeight() > 400) {width = 600;height = 250;} else {width = imageIcon.getIconWidth();height = imageIcon.getIconHeight();}// 設(shè)置圖片大小imageIcon.setImage(imageIcon.getImage().getScaledInstance(width, height, 0));// 為圖片名稱添加按鈕,用于打開(kāi)圖片JButton button = new JButton(fileName);button.setFont(new Font('宋體', Font.PLAIN, 20));button.setBackground(Color.WHITE);button.setBorderPainted(false);button.setFocusPainted(false);// 獲取整個(gè)展示面板的內(nèi)容,方便圖片文件的插入Document document = showPane.getDocument();try {// 插入圖片showPane.insertIcon(imageIcon);// 換行document.insertString(document.getLength(), 'n', new SimpleAttributeSet());// 插入按鈕,也就是圖片名稱showPane.insertComponent(button);document.insertString(document.getLength(), 'n', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 為按鈕添加點(diǎn)擊事件button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubtry {// 實(shí)現(xiàn)打開(kāi)文件功能File file = new File(path);Desktop.getDesktop().open(file);} catch (IOException e2) {// TODO Auto-generated catch blocke2.printStackTrace();}}});}// 把文件顯示在展示面板中public void writeFile(String path, String fileName) {// 獲取固定文件圖標(biāo)Icon fileImage = new ImageIcon('src/pictures/document.png');// 為名稱添加按鈕JButton button = new JButton(fileName);button.setFont(new Font('宋體', Font.PLAIN, 20));button.setBackground(Color.WHITE);button.setBorderPainted(false);button.setFocusPainted(false);// 獲取面板內(nèi)容Document document = showPane.getDocument();try {showPane.insertIcon(fileImage);showPane.insertComponent(button);document.insertString(document.getLength(), 'n', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}button.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubtry {// 實(shí)現(xiàn)打開(kāi)文件功能File file = new File(path);Desktop.getDesktop().open(file);} catch (IOException e2) {// TODO Auto-generated catch blocke2.printStackTrace();}}});}}
七、發(fā)送表情包
通過(guò)主界面表情包按鈕可以打開(kāi)表情包窗口
點(diǎn)擊表情包,可以發(fā)送表情包
表情包界面
package frame;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JTextPane;import javax.swing.text.BadLocationException;import javax.swing.text.Document;import javax.swing.text.SimpleAttributeSet;import function.SaveRecords;/** * 該類實(shí)現(xiàn)表情包窗體 * * @author 360°順滑 * * @date 2020/05/03 * */public class EmojiFrame {//展示面板private JTextPane showPane;//表情包按鈕private JButton[] buttons = new JButton[55];//表情包圖片private ImageIcon[] icons = new ImageIcon[55];//表情包對(duì)話框private JDialog emojiJDialog;//賬號(hào)private String userName;public EmojiFrame(JTextPane showPane,String userName) {this.showPane = showPane;this.userName = userName;}//表情包窗體public void init() {//用對(duì)話框來(lái)裝表情包emojiJDialog = new JDialog();emojiJDialog.setTitle('表情包');emojiJDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);emojiJDialog.setLayout(new GridLayout(6, 9));emojiJDialog.setBounds(490, 263, 500, 400);emojiJDialog.setBackground(Color.WHITE);ImageIcon image = new ImageIcon('src/pictures/emoji.png');emojiJDialog.setIconImage(image.getImage());//表情包用按鈕來(lái)實(shí)現(xiàn),主要是可以添加監(jiān)聽(tīng)事件,點(diǎn)擊后可以實(shí)現(xiàn)發(fā)送for (int i = 1; i <= 54; i++) {String path = 'src/pictures/emoji_' + i + '.png';icons[i] = new ImageIcon(path);buttons[i] = new JButton(icons[i]);buttons[i].setBackground(Color.WHITE);buttons[i].setBorder(null);buttons[i].setBorderPainted(false);buttons[i].setSize(20, 20);buttons[i].setFocusPainted(false);emojiJDialog.add(buttons[i]);}emojiJDialog.setVisible(true);//添加監(jiān)聽(tīng)事件addListen();}//監(jiān)聽(tīng)事件public void addListen() {//為每一個(gè)按鈕添加監(jiān)聽(tīng)事件for(int i=1;i<=54;i++) {String path = 'src/pictures/emoji_' + i + '.png';buttons[i].addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub//獲取圖片ImageIcon imageIcon = new ImageIcon(path);// 獲取日期Date date = new Date();SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss');String input = dateFormat.format(date) + 'n';Document document = showPane.getDocument();try {//寫(xiě)入日期document.insertString(document.getLength(), input, new SimpleAttributeSet());//插入圖片showPane.insertIcon(imageIcon);//換行document.insertString(document.getLength(), 'nn', new SimpleAttributeSet());} catch (BadLocationException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}// 保存路徑到對(duì)應(yīng)的賬號(hào)信息里,因?yàn)橛玫氖墙^對(duì)路徑,所以要根據(jù)實(shí)際來(lái)修改String saveText = input + 'D:eclipse jeeFileTransfer' + path + 'nn';SaveRecords records = new SaveRecords(userName, saveText);records.saveRecords();emojiJDialog.setVisible(false);}});}}}
發(fā)送表情包
//該方法寫(xiě)在FileSend類//發(fā)送表情包功能public void sendEmoji(String path) {// 獲取圖片ImageIcon imageIcon = new ImageIcon(path);// 獲取日期Date date = new Date();SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy-MM--dd HH:mm:ss');String input = dateFormat.format(date) + 'n';// 獲取整個(gè)展示面板的內(nèi)容,方便圖片文件的插入Document document = textShowPane.getDocument();try {// 插入日期document.insertString(document.getLength(), input, new SimpleAttributeSet());// 插入圖片textShowPane.insertIcon(imageIcon);document.insertString(document.getLength(), 'nn', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 輸入框重新清空textInputPane.setText('');}
八、查看歷史
記錄通過(guò)主界面的歷史記錄按鈕可以打開(kāi)歷史記錄窗口
歷史記錄界面
package frame;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Dimension;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.Box;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextField;import javax.swing.JTextPane;import function.ClearRecords;import function.FindRecords;import function.RecordsEcho;/** * 該類實(shí)現(xiàn)歷史記錄窗口 * * @author 360°順滑 * * @date 2020/05/02 * */public class HistoricRecordsFrame {private String userName;private JTextPane textShowPane;private JFrame historicRecordsFrame;private JButton findRecordsButton;private JButton clearRecordsButton;private JTextField searchTextField;private JTextPane recordsShowPane;private Box clearBox;public HistoricRecordsFrame(String userName,JTextPane textShowPane) {this.userName = userName;this.textShowPane = textShowPane;}public void init() {// 搜索文本框searchTextField = new JTextField();searchTextField.setFont(new Font('宋體', 0, 25));// 查找記錄按鈕findRecordsButton = new JButton('查找記錄');findRecordsButton.setFont(new Font('行楷', Font.PLAIN, 20));findRecordsButton.setBackground(Color.WHITE);findRecordsButton.setBorderPainted(false);findRecordsButton.setFocusPainted(false);// 將搜索文本框和搜索按鈕放入Box容器Box searchBox = Box.createHorizontalBox();searchBox.setPreferredSize(new Dimension(900, 47));searchBox.setBackground(Color.white);searchBox.add(Box.createHorizontalStrut(35));searchBox.add(searchTextField);searchBox.add(Box.createHorizontalStrut(20));searchBox.add(findRecordsButton);searchBox.add(Box.createHorizontalStrut(25));// 顯示文本窗格recordsShowPane = new JTextPane();recordsShowPane.setSize(900, 600);recordsShowPane.setBackground(Color.WHITE);recordsShowPane.setEditable(false);recordsShowPane.setBorder(null);recordsShowPane.setFont(new Font('宋體', 0, 25));// 顯示文本窗格添加滾動(dòng)條JScrollPane scrollShowPane = new JScrollPane(recordsShowPane);// 清空記錄按鈕clearRecordsButton = new JButton('清空記錄');clearRecordsButton.setFont(new Font('行楷', Font.PLAIN, 20));clearRecordsButton.setBackground(Color.WHITE);clearRecordsButton.setBorderPainted(false);clearRecordsButton.setFocusable(false);// Box容器并添加清空記錄按鈕clearBox = Box.createHorizontalBox();clearBox.setPreferredSize(new Dimension(1000, 60));clearBox.setBackground(Color.white);clearBox.add(Box.createVerticalStrut(5));clearBox.add(clearRecordsButton);clearBox.add(Box.createVerticalStrut(5));// 設(shè)置主窗體historicRecordsFrame = new JFrame('歷史記錄');historicRecordsFrame.setSize(900, 700);historicRecordsFrame.setLocationRelativeTo(null);historicRecordsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);// 改變窗體logoImageIcon image = new ImageIcon('src/pictures/historicRecordsLogo.png');historicRecordsFrame.setIconImage(image.getImage());historicRecordsFrame.setLayout(new BorderLayout());// 添加窗體以上兩個(gè)主要容器historicRecordsFrame.add(searchBox, BorderLayout.NORTH);historicRecordsFrame.add(scrollShowPane, BorderLayout.CENTER);historicRecordsFrame.add(clearBox, BorderLayout.SOUTH);historicRecordsFrame.setVisible(true);addListen();RecordsEcho recordsEcho = new RecordsEcho(userName, recordsShowPane);recordsEcho.read();}//添加按鈕監(jiān)聽(tīng)事件public void addListen() {//清空歷史記錄監(jiān)聽(tīng)事件clearRecordsButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubnew ClearRecords(userName,textShowPane,recordsShowPane).clear();}});//查找記錄監(jiān)聽(tīng)事件findRecordsButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubFindRecords findRecords = new FindRecords(recordsShowPane,userName,searchTextField.getText());findRecords.find();}});}}
歷史記錄回顯的代碼上面已經(jīng)給了,這里就不貼了。
還有一點(diǎn)功能值得一提,就是點(diǎn)擊歷史記錄中的圖片文件可以直接打開(kāi)!
九、查找歷史記錄
輸入關(guān)鍵字點(diǎn)擊查找記錄按鈕可以實(shí)現(xiàn)歷史記錄的查找,找不到則顯示“無(wú)相關(guān)記錄!”
查找歷史記錄
package function;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.swing.JTextPane;import javax.swing.text.BadLocationException;import javax.swing.text.Document;import javax.swing.text.SimpleAttributeSet;/** * 該類實(shí)現(xiàn)查找歷史記錄 * * 這段代碼說(shuō)實(shí)話,寫(xiě)得有點(diǎn)糟,本來(lái)后期要優(yōu)化,但是有點(diǎn)難搞,就這樣吧,將就著看! * * * @author 360°順滑 * * @date 2020/05/02 */public class FindRecords {private JTextPane recordsShowPane;private String userName;private String keywords;public FindRecords(JTextPane recordsShowPane, String userName, String keywords) {this.recordsShowPane = recordsShowPane;this.userName = userName;this.keywords = keywords;}// 該方法包括查找文本、圖片、文件,因?yàn)橐徊媸褂茫詫?xiě)在一起了public void find() {// 如果查找的不為空if (!(keywords.equals(''))) {// 查找相關(guān)賬號(hào)歷史記錄File file = new File('src/txt/' + userName + '.txt');FileReader fileReader = null;BufferedReader bufferedReader = null;try {fileReader = new FileReader(file);bufferedReader = new BufferedReader(fileReader);String str = '';String str1 = null;// 先把所有文本找到while ((str1 = bufferedReader.readLine()) != null) {if (str1.equals(''))str += 'n';elsestr = str + str1 + 'n';}// 正則表達(dá)式匹配要找的內(nèi)容Pattern pattern = Pattern.compile('.+n.*' + keywords + '.*nn');Matcher matcher = pattern.matcher(str);// 標(biāo)記有沒(méi)有找到boolean isExist = false;// 標(biāo)記是否第一次找到boolean oneFind = false;// 如果找到了while (matcher.find()) {isExist = true;// 正則表達(dá)式匹配是否為文件圖片路徑Pattern pattern1 = Pattern.compile('.+[.].+');Matcher matcher1 = pattern1.matcher(matcher.group());// 如果是文件或者圖片if (matcher1.find()) {// 截取日期int index3 = matcher.group().indexOf('n');String date = matcher.group().substring(0, index3);// 獲得文件名int index1 = matcher.group().lastIndexOf('');int index2 = matcher.group().lastIndexOf('nn');String fileName = matcher.group().substring(index1 + 1, index2);// 圖片的情況if (fileName.endsWith('.png') || fileName.endsWith('.jpg') || fileName.endsWith('.jpeg')|| fileName.endsWith('gif')) {Pattern pattern2 = Pattern.compile('[emoji_].+[.].+');Matcher matcher2 = pattern2.matcher(fileName);// 如果是表情包則不需要添加名稱if (matcher2.find()) {if (!oneFind) {// 寫(xiě)入日期recordsShowPane.setText(date + 'n');// 插入表情包和名稱RecordsEcho echo = new RecordsEcho(fileName, recordsShowPane);echo.writeEmoji(matcher1.group());Document document = recordsShowPane.getDocument();try {document.insertString(document.getLength(), 'n', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}oneFind = true;} else { // 不是第一次就直接寫(xiě)入Document document = recordsShowPane.getDocument();try {document.insertString(document.getLength(), date + 'n',new SimpleAttributeSet());RecordsEcho echo = new RecordsEcho(fileName, recordsShowPane);echo.writeEmoji(matcher1.group());document.insertString(document.getLength(), 'n', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}// 不是表情包的圖片else {// 如果是第一次找到,要先清空再寫(xiě)入if (!oneFind) {// 寫(xiě)入日期recordsShowPane.setText(date + 'n');// 插入圖片和名稱RecordsEcho echo = new RecordsEcho(fileName, recordsShowPane);echo.writeImage(matcher1.group(), fileName);// 換行Document document = recordsShowPane.getDocument();try {document.insertString(document.getLength(), 'n', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 標(biāo)記不是第一次了oneFind = true;} else { // 不是第一次找到就直接寫(xiě)入Document document = recordsShowPane.getDocument();try {document.insertString(document.getLength(), date + 'n',new SimpleAttributeSet());RecordsEcho echo = new RecordsEcho(fileName, recordsShowPane);echo.writeImage(matcher1.group(), fileName);document.insertString(document.getLength(), 'n', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}} else { // 文件的情況// 第一次找到if (!oneFind) {// 清空并寫(xiě)入日期recordsShowPane.setText(date + 'n');// 插入文件圖片以及名稱RecordsEcho echo = new RecordsEcho(fileName, recordsShowPane);echo.writeFile(matcher1.group(), fileName);// 換行Document document = recordsShowPane.getDocument();try {document.insertString(document.getLength(), 'n', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}oneFind = true;} else { // 不是第一次找到Document document = recordsShowPane.getDocument();try {document.insertString(document.getLength(), date + 'n', new SimpleAttributeSet());RecordsEcho echo = new RecordsEcho(fileName, recordsShowPane);echo.writeFile(matcher1.group(), fileName);document.insertString(document.getLength(), 'n', new SimpleAttributeSet());} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}} else { // 查找的是文本String s = '';for(int i = 0; i < matcher.group().length(); i++) {//因?yàn)椴檎业降淖址掌冢砸獜?0開(kāi)始if(i>20 && (i-20) % 30 == 0)s += 'n';s
相關(guān)文章:
1. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫(huà)特效2. Android如何優(yōu)雅的處理重復(fù)點(diǎn)擊3. Python使用oslo.vmware管理ESXI虛擬機(jī)的示例參考4. VMware如何進(jìn)入BIOS方法5. opencv-python的RGB與BGR互轉(zhuǎn)方式6. HTML基礎(chǔ)詳解(下)7. Android Studio 3.6 正式版終于發(fā)布了,快來(lái)圍觀8. ASP.NET MVC使用Session會(huì)話保持表單狀態(tài)9. springboot全局字符編碼設(shè)置解決亂碼問(wèn)題10. SpringBoot后端接口的實(shí)現(xiàn)(看這一篇就夠了)
