Java 檔案傳輸助手的實現(單機版)
專案介紹
用 Java 實現單機版的檔案傳輸助手專案。
涉及技術知識:
- Swing 元件
- I/O流
- 正則表示式
- Java 事務處理機制
基礎功能:
- 登入、註冊
- 傳送文字
- 傳送圖片、檔案
- 文字、圖片、檔案的資訊記錄
- 歷史記錄的儲存、回顯及清空
- 資訊傳送的日期
- 退出
高階功能:
- 傳送表情包
- 檢視和查詢歷史記錄
- 點選歷史記錄的檔案圖片能直接開啟
- 拖拽輸入資訊、圖片、檔案
功能總覽:
功能實現
一、登入
進入登入介面
未輸入賬號,登入彈出提示
輸入賬號,但未輸入密碼登入時彈出提示
賬號或者密碼輸入錯誤登入時彈出提示
登入成功時進入主介面
登入介面:
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) { // 建立窗體 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); // 建立內容面板 Container container = loginJFrame.getContentPane(); container.setLayout(null); // 建立“賬號”標籤 userNameLabel = new JLabel("賬號:"); userNameLabel.setFont(new Font("行楷",Font.BOLD,25)); userNameLabel.setBounds(60,25,100,100); container.add(userNameLabel); // 建立輸入賬號文字框 userNameTextField = new JTextField(); userNameTextField.setFont(new Font("黑體",Font.PLAIN,23)); userNameTextField.setBounds(133,61,280,33); container.add(userNameTextField); // 建立“密碼”標籤 passwordLabel = new JLabel("密碼:"); passwordLabel.setFont(new Font("行楷",25)); passwordLabel.setBounds(60,90,100); container.add(passwordLabel); // 建立輸入密碼文字框 passwordField = new JPasswordField(); passwordField.setBounds(133,127,33); passwordField.setFont(new Font("Arial",23)); container.add(passwordField); // 建立登入按鈕 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); // 建立註冊按鈕 registerButton = new JButton("註冊"); registerButton.setBounds(282,40); registerButton.setFont(new Font("微軟雅黑",18)); registerButton.setBackground(Color.WHITE); registerButton.setFocusPainted(false); registerButton.setBorderPainted(false); container.add(registerButton); // 顯示窗體 loginJFrame.setVisible(true); addListen(); } // 為按鈕新增監聽器 public static void addListen() { // 為登入按鈕新增監聽事件 loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub // 建立Login物件並把LoginFrame的文字框內容作為引數傳過去 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); } } } } }); // 為註冊按鈕新增監聽事件 registerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub // 隱藏當前登入視窗 loginJFrame.setVisible(false); // 開啟註冊視窗 new RegisterFrame().init(); } }); } /* * 由於各個標籤長度不同,所以為了介面美觀,就寫了三個彈出對話方塊而不是一個! * */ // 未輸入賬號時彈出提示對話方塊 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("未輸入賬號!"); jLabel.setFont(new Font("行楷",21)); jLabel.setBounds(82,200,100); jDialog.add(jLabel); JButton button = new JButton("確定"); button.setBounds(105,80,40); button.setFont(new Font("微軟雅黑",18)); button.setBackground(Color.WHITE); button.setFocusPainted(false); button.setBorderPainted(false); jDialog.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub jDialog.dispose(); } }); jDialog.setVisible(true); } // 未輸入密碼時彈出提示對話方塊 public static void emptyPasswordJDialog(JFrame jFrame) { JDialog jDialog = new JDialog(jFrame,200); jDialog.setLocationRelativeTo(null); ImageIcon image = new ImageIcon("src/pictures/warn.png"); jDialog.setIconImage(image.getImage()); JLabel jLabel = new JLabel("未輸入密碼!"); jLabel.setFont(new Font("行楷",18)); button.setBackground(Color.WHITE); button.setFocusPainted(false); button.setBorderPainted(false); jDialog.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub jDialog.dispose(); } }); jDialog.setVisible(true); } // 賬號或密碼輸入錯誤! public static void failedLoginJDialog(JFrame jFrame) { JDialog jDialog = new JDialog(jFrame,200); jDialog.setLocationRelativeTo(null); ImageIcon image = new ImageIcon("src/pictures/warn.png"); jDialog.setIconImage(image.getImage()); JLabel jLabel = new JLabel("賬號或密碼輸入錯誤!"); jLabel.setFont(new Font("行楷",20)); jLabel.setBounds(47,18)); button.setBackground(Color.WHITE); button.setFocusPainted(false); button.setBorderPainted(false); jDialog.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub jDialog.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; } //判斷賬號是否為空方法 public boolean isEmptyUserName() { if (userNameTextField.getText().equals("")) return true; else return false; } //判斷密碼是否為空方法 public boolean isEmptyPassword() { //操作密碼框文字要先將其轉換為字串 if ("".equals(new String(passwordField.getPassword()))) return true; else return false; } // 查詢是否存在該賬號密碼 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 block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fileReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (vis) return true; else return 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("宋體",25)); // 顯示文字窗格新增滾動條 scrollShowPane = new JScrollPane(showPane); // 表情包按鈕並新增圖示 Icon expressionIcon = new ImageIcon("src/pictures/expression.png"); expressionButton = new JButton(expressionIcon); expressionButton.setBackground(Color.WHITE); expressionButton.setFocusPainted(false); expressionButton.setBorderPainted(false); // 檔案按鈕並新增圖示 Icon fileIcon = new ImageIcon("src/pictures/file.png"); fileButton = new JButton(fileIcon); fileButton.setBackground(Color.WHITE); fileButton.setFocusPainted(false); fileButton.setBorderPainted(false); // 歷史記錄按鈕並新增圖示 Icon historicRecordsIcon = new ImageIcon("src/pictures/historicRecords.png"); historicRecordsButton = new JButton(historicRecordsIcon); historicRecordsButton.setBackground(Color.WHITE); historicRecordsButton.setFocusPainted(false); historicRecordsButton.setBorderPainted(false); // 按鈕Box容器新增三個按鈕 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("宋體",24)); inputPane.setBackground(Color.WHITE); JScrollPane scrollInputPane = new JScrollPane(inputPane); // 輸入區域的Box容器 inputBox = Box.createHorizontalBox(); inputBox.setPreferredSize(new Dimension(1000,150)); inputBox.add(scrollInputPane); // 傳送按鈕 sendButton = new JButton("傳送(S)"); sendButton.setFont(new Font("行楷",20)); sendButton.setBackground(Color.WHITE); sendButton.setFocusPainted(false); sendButton.setBorderPainted(false); // 傳送Box容器並添加發送按鈕 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個Box totalBox = 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)); // 設定主窗體 mainFrame = new JFrame("檔案傳輸助手"); mainFrame.setSize(950,800); mainFrame.setLocationRelativeTo(null); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 改變窗體logo image = new ImageIcon("src/pictures/logo.png"); mainFrame.setIconImage(image.getImage()); mainFrame.setLayout(new BorderLayout()); // 新增窗體以上兩個主要容器 mainFrame.add(scrollShowPane,BorderLayout.CENTER); mainFrame.add(totalBox,BorderLayout.SOUTH); mainFrame.setVisible(true); // 新增監聽器 addListen(); // 資訊記錄回顯到展示面板 RecordsEcho echo = new RecordsEcho(userName,showPane); echo.read(); } // 提示對話方塊 public static void warnJDialog(String information) { JDialog jDialog = new JDialog(mainFrame,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("微軟雅黑",18)); jLabel.setBounds(65,18)); button.setBackground(Color.WHITE); button.setFocusPainted(false); button.setBorderPainted(false); jDialog.add(button); // 為彈出對話方塊按鈕新增監聽事件 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub jDialog.dispose(); } }); jDialog.setVisible(true); } // 新增監聽事件 @SuppressWarnings("unused") public void addListen() { /* * 為輸入文字新增目標監聽器 */ // 建立拖拽目標監聽器 DropTargetListener listener = new DropTargetFile(inputPane); // 在 inputPane上註冊拖拽目標監聽器 DropTarget dropTarget = new DropTarget(inputPane,DnDConstants.ACTION_COPY_OR_MOVE,listener,true); // 傳送按鈕監聽事件 sendButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub TextSend textSend = new TextSend(showPane,inputPane,userName); textSend.sendText(); } }); // 輸入框新增鍵盤事件 inputPane.addKeyListener(new KeyListener() { // 發生擊鍵事件時被觸發 @Override public void keyTyped(KeyEvent e) { } // 按鍵被釋放時被觸發 @Override public void keyReleased(KeyEvent e) { } // 按鍵被按下時被觸發 @Override public 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 block e1.printStackTrace(); } // 否則傳送 } else if (e.getKeyCode() == KeyEvent.VK_ENTER) { TextSend textSend = new TextSend(showPane,userName); textSend.sendText(); } } }); // 表情包按鈕監聽事件 expressionButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub new EmojiFrame(showPane,userName).init(); } }); // 檔案按鈕監聽事件 fileButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub FileSend fileSend = new FileSend(userName,showPane,inputPane); fileSend.send(); } }); // 歷史記錄按鈕監聽事件 historicRecordsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub new HistoricRecordsFrame(userName,showPane).init(); } }); } }
登入之前如果沒有賬號就得先註冊一個,那麼進入註冊功能!
二、註冊
點選登入介面的註冊按鈕,進入註冊介面
未輸入賬號進行註冊時
輸入賬號但未輸入密碼或者確認密碼進行註冊時
密碼和確認密碼不一致時進行註冊
賬號已存在進行註冊時
註冊成功時
點選確定按鈕或者關閉視窗後返回登入介面
如果取消註冊,直接點選返回按鈕就可以返回登入介面了
註冊介面
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; /** * * 檔案傳輸助手註冊介面 * * @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() { // 建立窗體 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); // 建立內容面板 Container container = registerJFrame.getContentPane(); container.setLayout(null); // 建立“賬號”標籤 userNameLabel = new JLabel("賬號:"); userNameLabel.setFont(new Font("行楷",25)); userNameLabel.setBounds(97,23)); userNameTextField.setBounds(170,25)); passwordLabel.setBounds(97,100); container.add(passwordLabel); // 建立輸入密碼文字框 passwordField = new JPasswordField(); passwordField.setBounds(170,125,23)); container.add(passwordField); // 建立“確認密碼”標籤 passwordAgainLabel = new JLabel("確認密碼:"); passwordAgainLabel.setFont(new Font("行楷",25)); passwordAgainLabel.setBounds(45,150,130,100); container.add(passwordAgainLabel); // 建立確認密碼文字框 passwordAgainField = new JPasswordField(); passwordAgainField.setBounds(170,33); passwordAgainField.setFont(new Font("Arial",23)); container.add(passwordAgainField); // 建立返回按鈕 goBackButton = new JButton("返回"); goBackButton.setBounds(200,260,40); goBackButton.setFont(new Font("微軟雅黑",18)); goBackButton.setBackground(Color.WHITE); goBackButton.setFocusPainted(false); goBackButton.setBorderPainted(false); container.add(goBackButton); // 建立註冊按鈕 registerButton = new JButton("註冊"); registerButton.setBounds(330,18)); registerButton.setBackground(Color.WHITE); registerButton.setFocusPainted(false); registerButton.setBorderPainted(false); container.add(registerButton); // 顯示窗體 registerJFrame.setVisible(true); addListen(); } // 為按鈕新增監聽事件 public void addListen() { // 為註冊按鈕新增監聽事件 registerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub // 建立register物件,同時將RegisterFrame的文字框內容作為引數傳過去 Register register = new Register(userNameTextField,passwordField,passwordAgainField); // 判斷輸入賬號是否為空 if (register.isEmptyUserName()) { emptyUserName(registerJFrame); } else { // 判斷輸入密碼是否為空 if (register.isEmptyPassword()) { emptyPasswordJDialog(registerJFrame); } else { // 判斷密碼和確認密碼是否一致 if (register.isSamePassWord()) { // 判斷賬號是否已存在 if (!register.isExistAccount()) { // 註冊成功!!! register.saveInformation(); registerJFrame.dispose(); userNameTextField.setText(""); passwordField.setText(""); passwordAgainField.setText(""); new LoginFrame(); LoginFrame.loginJFrame.setVisible(true); successRegisterJDialog(registerJFrame); } else existAccountJDialog(registerJFrame); } else { differentPasswordJDialog(registerJFrame); passwordField.setText(""); passwordAgainField.setText(""); } } } } }); // 為返回按鈕新增監聽事件 goBackButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 銷燬註冊視窗 registerJFrame.dispose(); // 重新顯示登入視窗 new LoginFrame(); LoginFrame.loginJFrame.setVisible(true); } }); } /* * 由於各個標籤長度不同,所以為了介面美觀,就寫了三個彈出對話方塊而不是一個! * */ // 未輸入賬號時彈出提示對話方塊 public void emptyUserName(JFrame jFrame) { JDialog jDialog = new JDialog(jFrame,200); jDialog.setLocationRelativeTo(null); ImageIcon image = new ImageIcon("src/pictures/warn.png"); jDialog.setIconImage(image.getImage()); JLabel jLabel = new JLabel("未輸入使用者名稱!"); jLabel.setFont(new Font("行楷",21)); jLabel.setBounds(73,18)); button.setBackground(Color.WHITE); button.setFocusPainted(false); button.setBorderPainted(false); jDialog.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub jDialog.dispose(); } }); jDialog.setVisible(true); } // 未輸入密碼時彈出提示對話方塊 public void emptyPasswordJDialog(JFrame jFrame) { JDialog jDialog = new JDialog(jFrame,18)); button.setBackground(Color.WHITE); button.setFocusPainted(false); button.setBorderPainted(false); jDialog.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub jDialog.dispose(); } }); jDialog.setVisible(true); } // 密碼和確認密碼不一致時彈出提示框 public void differentPasswordJDialog(JFrame jFrame) { JDialog jDialog = new JDialog(jFrame,200); jDialog.setLocationRelativeTo(null); ImageIcon image = new ImageIcon("src/pictures/warn.png"); jDialog.setIconImage(image.getImage()); JLabel jLabel = new JLabel("輸入密碼不一致!"); jLabel.setFont(new Font("行楷",21)); jLabel.setBounds(63,18)); button.setBackground(Color.WHITE); button.setFocusPainted(false); button.setBorderPainted(false); jDialog.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub jDialog.dispose(); } }); jDialog.setVisible(true); } // 已存在賬號彈出提示對話方塊 public void existAccountJDialog(JFrame jFrame) { JDialog jDialog = new JDialog(jFrame,200); jDialog.setLocationRelativeTo(null); ImageIcon image = new ImageIcon("src/pictures/warn.png"); jDialog.setIconImage(image.getImage()); JLabel jLabel = new JLabel("該賬號已存在!"); jLabel.setFont(new Font("行楷",18)); button.setBackground(Color.WHITE); button.setFocusPainted(false); button.setBorderPainted(false); jDialog.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub jDialog.dispose(); } }); jDialog.setVisible(true); } // 成功註冊對話方塊 public void successRegisterJDialog(JFrame jFrame) { JDialog jDialog = new JDialog(jFrame,200); jDialog.setLocationRelativeTo(null); ImageIcon image = new ImageIcon("src/pictures/warn.png"); jDialog.setIconImage(image.getImage()); JLabel jLabel = new JLabel("註冊成功!"); jLabel.setFont(new Font("行楷",18)); button.setBackground(Color.WHITE); button.setFocusPainted(false); button.setBorderPainted(false); jDialog.add(button); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub // 銷燬提示對話方塊 jDialog.dispose(); } }); jDialog.setVisible(true); } }
註冊判斷
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; /** * 檔案傳輸助手註冊功能 * * @author:360°順滑 * * @date:2020/04/28 ~ 2020/04/29 * */ public class Register { JTextField userNameTextField; JPasswordField passwordField; JPasswordField passwordAgainField; //將RegisterFrame引數傳入進來 public Register(JTextField userNameTextField,JPasswordField passwordField,JPasswordField passwordAgainField) { this.userNameTextField = userNameTextField; this.passwordField = passwordField; this.passwordAgainField = passwordAgainField; } //判斷賬號是否為空方法 public boolean isEmptyUserName() { if (userNameTextField.getText().equals("")) return true; else return false; } //判斷密碼是否為空方法 public boolean isEmptyPassword() { //操作密碼框文字要先將其轉換為字串 if ("".equals(new String(passwordField.getPassword())) || "".equals(new String(passwordAgainField.getPassword()))) return true; else return false; } //判斷密碼和輸入密碼是否一致方法 public boolean isSamePassWord() { //操作密碼框文字要先將其轉換為字串 if (new String(passwordField.getPassword()).equals(new String(passwordAgainField.getPassword()))) return true; else return false; } //判斷賬號是否已存在方法 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); //正則表示式 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 block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.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 block e.printStackTrace(); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
三、傳送文字
輸入文字後可以點擊發送按鈕傳送,也可以通過鍵盤Enter鍵傳送
傳送空白資訊時彈出提示,提示框程式碼在主介面類裡
傳送文字:
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; /** * 實現傳送訊息,並儲存到資訊記錄 * * @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()))) { // 獲取日期並設定日期格式 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; // 判斷是否為第一個檔案 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(),new SimpleAttributeSet()); } else { new RecordsEcho(userName,new SimpleAttributeSet()); } } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else {// 檔案的情況 Document document = textShowPane.getDocument(); try { if (isFirst) { isFirst = false; document.insertString(document.getLength(),textShowPane).writeFile(matcher.group(),new SimpleAttributeSet()); } } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (!isFile) { // 實現傳送文字太長自動換行 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 + "\n\n",attributeSet); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 把資訊儲存到對應的使用者本地歷史記錄txt檔案 SaveRecords records = new SaveRecords(userName,inputText + textInputPane.getText() + "\n\n"); records.saveRecords(); textInputPane.setText(""); } else { new MainFrame(); MainFrame.warnJDialog("不能傳送空白資訊!"); } } }
其實這個類不單單只是傳送文字這麼簡單,因為後續實現了拖拽傳送檔案,拖拽後會在輸入框自動輸入檔案路徑,實現的程式碼有關聯,就寫在這裡了。
四、傳送圖片 、檔案和表情包
圖片檔案的傳送主要是通過開啟本地瀏覽傳送的
傳送檔案、圖片、表情包:
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; /** * 實現開啟檔案按鈕傳送圖片檔案表情包 * * @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; } // 彈出選擇框並判斷髮送的是檔案還是圖片 public void send() { // 點選檔案按鈕可以開啟檔案選擇框 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); } } } // 傳送圖片 public void sendImage(String path,String fileName) { // 獲取圖片 ImageIcon imageIcon = new ImageIcon(path); // 如果圖片比整個介面大則調整大小 int width,height; if (imageIcon.getIconWidth() > 950 || imageIcon.getIconHeight() > 400) { width = 600; height = 250; } else { width = imageIcon.getIconWidth(); height = imageIcon.getIconHeight(); } // 設定圖片大小 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"; // 為圖片名稱新增按鈕,用於開啟圖片 JButton button = new JButton(fileName); button.setFont(new Font("宋體",20)); button.setBackground(Color.WHITE); button.setBorderPainted(false); button.setFocusPainted(false); // 獲取整個展示面板的內容,方便圖片檔案的插入 Document document = textShowPane.getDocument(); try { // 插入日期 document.insertString(document.getLength(),input,new SimpleAttributeSet()); // 插入圖片 textShowPane.insertIcon(imageIcon); // 換行 document.insertString(document.getLength(),new SimpleAttributeSet()); // 插入按鈕,也就是圖片名稱 textShowPane.insertComponent(button); document.insertString(document.getLength(),"\n\n",new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 為按鈕新增點選事件 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { // 實現開啟檔案功能 File file = new File(path); Desktop.getDesktop().open(file); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } }); // 輸入框重新清空 textInputPane.setText(""); // 儲存路徑到對應的賬號資訊裡 String saveText = input + path + "\n\n"; SaveRecords records = new SaveRecords(userName,saveText); records.saveRecords(); } // 傳送檔案 public void sendFile(String path,String fileName) { // 獲取固定檔案圖示 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("宋體",20)); button.setBackground(Color.WHITE); button.setBorderPainted(false); button.setFocusPainted(false); // 獲取面板內容 Document document = textShowPane.getDocument(); try { document.insertString(document.getLength(),new SimpleAttributeSet()); textShowPane.insertIcon(fileImage); textShowPane.insertComponent(button); document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } //為名稱按鈕新增監聽事件,實現開啟功能 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { // 實現開啟檔案功能 File file = new File(path); Desktop.getDesktop().open(file); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } }); textInputPane.setText(""); // 儲存路徑到對應的賬號資訊裡 String saveText = input + path + "\n\n"; SaveRecords records = new SaveRecords(userName,saveText); records.saveRecords(); } //傳送表情包功能 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"; // 獲取整個展示面板的內容,方便圖片檔案的插入 Document document = textShowPane.getDocument(); try { // 插入日期 document.insertString(document.getLength(),new SimpleAttributeSet()); // 插入圖片 textShowPane.insertIcon(imageIcon); document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 輸入框重新清空 textInputPane.setText(""); } }
五、儲存歷史記錄
傳送文字、圖片、檔案和表情包的資訊(文字或路徑)都要儲存到本地,以便歷史資訊的回顯,查詢歷史資訊。
package function; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * 該類實現儲存資訊記錄 * * * @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); // 檔案不存在就建立一個 if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.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 block e.printStackTrace(); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
六、歷史記錄回顯
登入後進入主介面或者進入歷史記錄介面會看到該賬號以前傳送過的資訊記錄
歷史記錄回顯:
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; /** * * 該類實現歷史記錄回顯 * * @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() { // 對應賬號的資訊記錄文字 File file = new File("src/txt/" + userName + ".txt"); // 檔案不存在就建立一個 if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } FileReader fileReader = null; BufferedReader bufferedReader = null; try { fileReader = new FileReader(file); bufferedReader = new BufferedReader(fileReader); // 正則表示式 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 { // 如果是文字則直接寫入 writeText(str); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fileReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.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 block e.printStackTrace(); } } public void writeEmoji(String path) { // 獲取圖片 ImageIcon imageIcon = new ImageIcon(path); // 獲取整個展示面板的內容,方便圖片檔案的插入 Document document = showPane.getDocument(); try { // 插入圖片 showPane.insertIcon(imageIcon); // 換行 document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 把圖片顯示在展示面板 public void writeImage(String path,String fileName) { // 獲取圖片 ImageIcon imageIcon = new ImageIcon(path); // 如果圖片比整個介面大則調整大小 int width,0)); // 為圖片名稱新增按鈕,用於開啟圖片 JButton button = new JButton(fileName); button.setFont(new Font("宋體",20)); button.setBackground(Color.WHITE); button.setBorderPainted(false); button.setFocusPainted(false); // 獲取整個展示面板的內容,方便圖片檔案的插入 Document document = showPane.getDocument(); try { // 插入圖片 showPane.insertIcon(imageIcon); // 換行 document.insertString(document.getLength(),new SimpleAttributeSet()); // 插入按鈕,也就是圖片名稱 showPane.insertComponent(button); document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 為按鈕新增點選事件 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { // 實現開啟檔案功能 File file = new File(path); Desktop.getDesktop().open(file); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } }); } // 把檔案顯示在展示面板中 public void writeFile(String path,String fileName) { // 獲取固定檔案圖示 Icon fileImage = new ImageIcon("src/pictures/document.png"); // 為名稱新增按鈕 JButton button = new JButton(fileName); button.setFont(new Font("宋體",20)); button.setBackground(Color.WHITE); button.setBorderPainted(false); button.setFocusPainted(false); // 獲取面板內容 Document document = showPane.getDocument(); try { showPane.insertIcon(fileImage); showPane.insertComponent(button); document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { // 實現開啟檔案功能 File file = new File(path); Desktop.getDesktop().open(file); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } }); } }
七、傳送表情包
通過主介面表情包按鈕可以開啟表情包視窗
點選表情包,可以傳送表情包
表情包介面
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; /** * 該類實現表情包窗體 * * @author 360°順滑 * * @date 2020/05/03 * */ public class EmojiFrame { //展示面板 private JTextPane showPane; //表情包按鈕 private JButton[] buttons = new JButton[55]; //表情包圖片 private ImageIcon[] icons = new ImageIcon[55]; //表情包對話方塊 private JDialog emojiJDialog; //賬號 private String userName; public EmojiFrame(JTextPane showPane,String userName) { this.showPane = showPane; this.userName = userName; } //表情包窗體 public void init() { //用對話方塊來裝表情包 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()); //表情包用按鈕來實現,主要是可以新增監聽事件,點選後可以實現傳送 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); //新增監聽事件 addListen(); } //監聽事件 public void addListen() { //為每一個按鈕新增監聽事件 for(int i=1;i<=54;i++) { String path = "src/pictures/emoji_" + i + ".png"; buttons[i].addActionListener(new ActionListener() { @Override public 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 { //寫入日期 document.insertString(document.getLength(),new SimpleAttributeSet()); //插入圖片 showPane.insertIcon(imageIcon); //換行 document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // 儲存路徑到對應的賬號資訊裡,因為用的是絕對路徑,所以要根據實際來修改 String saveText = input + "D:\\eclipse jee\\FileTransfer\\" + path + "\n\n"; SaveRecords records = new SaveRecords(userName,saveText); records.saveRecords(); emojiJDialog.setVisible(false); } }); } } }
傳送表情包
//該方法寫在FileSend類 //傳送表情包功能 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"; // 獲取整個展示面板的內容,方便圖片檔案的插入 Document document = textShowPane.getDocument(); try { // 插入日期 document.insertString(document.getLength(),new SimpleAttributeSet()); // 插入圖片 textShowPane.insertIcon(imageIcon); document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 輸入框重新清空 textInputPane.setText(""); }
八、檢視歷史
記錄通過主介面的歷史記錄按鈕可以開啟歷史記錄視窗
歷史記錄介面
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; /** * 該類實現歷史記錄視窗 * * @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("宋體",25)); // 查詢記錄按鈕 findRecordsButton = new JButton("查詢記錄"); findRecordsButton.setFont(new Font("行楷",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("宋體",25)); // 顯示文字窗格新增滾動條 JScrollPane scrollShowPane = new JScrollPane(recordsShowPane); // 清空記錄按鈕 clearRecordsButton = new JButton("清空記錄"); clearRecordsButton.setFont(new Font("行楷",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)); // 設定主窗體 historicRecordsFrame = new JFrame("歷史記錄"); historicRecordsFrame.setSize(900,700); historicRecordsFrame.setLocationRelativeTo(null); historicRecordsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 改變窗體logo ImageIcon image = new ImageIcon("src/pictures/historicRecordsLogo.png"); historicRecordsFrame.setIconImage(image.getImage()); historicRecordsFrame.setLayout(new BorderLayout()); // 新增窗體以上兩個主要容器 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(); } //新增按鈕監聽事件 public void addListen() { //清空歷史記錄監聽事件 clearRecordsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub new ClearRecords(userName,textShowPane,recordsShowPane).clear(); } }); //查詢記錄監聽事件 findRecordsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub FindRecords findRecords = new FindRecords(recordsShowPane,userName,searchTextField.getText()); findRecords.find(); } }); } }
歷史記錄回顯的程式碼上面已經給了,這裡就不貼了。
還有一點功能值得一提,就是點選歷史記錄中的圖片檔案可以直接開啟!
九、查詢歷史記錄
輸入關鍵字點選查詢記錄按鈕可以實現歷史記錄的查詢,找不到則顯示“無相關記錄!”
查詢歷史記錄
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; /** * 該類實現查詢歷史記錄 * * 這段程式碼說實話,寫得有點糟,本來後期要優化,但是有點難搞,就這樣吧,將就著看! * * * @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; } // 該方法包括查詢文字、圖片、檔案,因為要交叉使用,所以寫在一起了 public void find() { // 如果查詢的不為空 if (!(keywords.equals(""))) { // 查詢相關賬號歷史記錄 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"; else str = str + str1 + "\n"; } // 正則表示式匹配要找的內容 Pattern pattern = Pattern.compile(".+\n.*" + keywords + ".*\n\n"); Matcher matcher = pattern.matcher(str); // 標記有沒有找到 boolean isExist = false; // 標記是否第一次找到 boolean oneFind = false; // 如果找到了 while (matcher.find()) { isExist = true; // 正則表示式匹配是否為檔案圖片路徑 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("\n\n"); 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) { // 寫入日期 recordsShowPane.setText(date + "\n"); // 插入表情包和名稱 RecordsEcho echo = new RecordsEcho(fileName,recordsShowPane); echo.writeEmoji(matcher1.group()); Document document = recordsShowPane.getDocument(); try { document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } oneFind = true; } else { // 不是第一次就直接寫入 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(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // 不是表情包的圖片 else { // 如果是第一次找到,要先清空再寫入 if (!oneFind) { // 寫入日期 recordsShowPane.setText(date + "\n"); // 插入圖片和名稱 RecordsEcho echo = new RecordsEcho(fileName,recordsShowPane); echo.writeImage(matcher1.group(),fileName); // 換行 Document document = recordsShowPane.getDocument(); try { document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 標記不是第一次了 oneFind = true; } else { // 不是第一次找到就直接寫入 Document document = recordsShowPane.getDocument(); try { document.insertString(document.getLength(),recordsShowPane); echo.writeImage(matcher1.group(),fileName); document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } else { // 檔案的情況 // 第一次找到 if (!oneFind) { // 清空並寫入日期 recordsShowPane.setText(date + "\n"); // 插入檔案圖片以及名稱 RecordsEcho echo = new RecordsEcho(fileName,recordsShowPane); echo.writeFile(matcher1.group(),fileName); // 換行 Document document = recordsShowPane.getDocument(); try { document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } oneFind = true; } else { // 不是第一次找到 Document document = recordsShowPane.getDocument(); try { document.insertString(document.getLength(),new SimpleAttributeSet()); RecordsEcho echo = new RecordsEcho(fileName,recordsShowPane); echo.writeFile(matcher1.group(),fileName); document.insertString(document.getLength(),new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } else { // 查詢的是文字 String s = ""; for(int i = 0; i < matcher.group().length(); i++) { //因為查詢到的字串包含日期,所以要從20開始 if(i>20 && (i-20) % 30 == 0) s += "\n"; s += matcher.group().charAt(i); } if (!oneFind) { recordsShowPane.setText(s); oneFind = true; } else { Document document = recordsShowPane.getDocument(); try { document.insertString(document.getLength(),s,new SimpleAttributeSet()); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } // 找不到的情況 if (!isExist) recordsShowPane.setText("\n\n\n 無相關記錄!"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fileReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { // 查詢為空的情況 recordsShowPane.setText("\n\n\n 無相關記錄!"); } } }
十、清空歷史記
錄點擊清空歷史記錄,所有資訊都會被刪除,包括本地資訊。
清空歷史資訊
package function; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.swing.JTextPane; /** * 該類實現清空歷史記錄的功能 * * @author 360°順滑 * * @date 2020/05/03 * */ public class ClearRecords { private JTextPane textShowPane; private JTextPane recordsShowPane; private String userName; public ClearRecords(String userName,JTextPane recordsShowPane) { this.userName = userName; this.textShowPane = textShowPane; this.recordsShowPane = recordsShowPane; } //把展示面板、輸入面板、本地資訊全部清空 public void clear() { textShowPane.setText(""); recordsShowPane.setText(""); String path = "src/txt/" + userName + ".txt"; File file = new File(path); FileWriter fileWriter = null; BufferedWriter bufferedWriter = null; try { fileWriter = new FileWriter(file); bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write("");; bufferedWriter.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
十一、拖拽輸入文字、圖片和檔案
通過拖拽將文字資訊(複製貼上)、圖片檔案路徑輸入到輸入框中,傳送後可以顯示圖片檔案。同時,拖拽可以同時拖多個檔案。
拖拽輸入文字檔案
package function; import java.awt.datatransfer.DataFlavor; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.io.File; import java.util.List; import javax.swing.JTextPane; import javax.swing.text.Document; import javax.swing.text.SimpleAttributeSet; /** * 該類實現拖拽檔案,複製貼上功能 * * 由於該功能第一次實現,所以部分程式碼是搬磚過來的 * * @author 360°順滑 * * @date 2020/05/03 */ public class DropTargetFile implements DropTargetListener { /** 用於顯示拖拽資料的面板 */ private JTextPane inputPane; public DropTargetFile(JTextPane inputPane) { this.inputPane = inputPane; } public void dragEnter(DropTargetDragEvent dtde) { } public void dragOver(DropTargetDragEvent dtde) { } public void dragExit(DropTargetEvent dte) { } public void dropActionChanged(DropTargetDragEvent dtde) { } public void drop(DropTargetDropEvent dtde) { boolean isAccept = false; try { /* * 判斷拖拽目標是否支援檔案列表資料(即拖拽的是否是檔案或資料夾,支援同時拖拽多個) */ if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { // 接收拖拽目標資料 dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); isAccept = true; // 以檔案集合的形式獲取資料 @SuppressWarnings("unchecked") List<File> files = (List<File>) dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor); // 把檔案路徑輸出到文字區域 if (files != null && files.size() > 0) { StringBuilder filePaths = new StringBuilder(); for (File file : files) { filePaths.append(file.getAbsolutePath() + "\n"); } Document document = inputPane.getDocument(); document.insertString(document.getLength(),filePaths.toString(),new SimpleAttributeSet()); } } } catch (Exception e) { e.printStackTrace(); } // 如果此次拖拽的資料是被接受的,則必須設定拖拽完成(否則可能會看到拖拽目標返回原位置,造成視覺上以為是不支援拖拽的錯誤效果) if (isAccept) { dtde.dropComplete(true); } } }
功能基本就是這樣了,還是有許多bug,但改不動了,後續有時間有機會再改進吧!!!
到此這篇關於Java 檔案傳輸助手的實現(單機版)的文章就介紹到這了,更多相關Java 檔案傳輸助手內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!