Java TCP swing 云笔记本

服务器server

package code;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Vector;
import java.awt.Font;
import java.awt.Dimension;

public class server {
    public LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();// 全局变量
    public String accountString =new String();
    public class ancestor extends JFrame {
        protected JPanel jPanel = new JPanel();
        protected ServerSocket ss = null;
        protected Socket s = null;
        protected String title = null;
        protected JTable jTable = null;
        protected JScrollPane jScrollPane = null;
        protected Vector<Vector<String>> data = new Vector<>();
        protected Vector<String> columnName = new Vector<>();

        public ancestor(String title) {
            super(title);
            this.title = title;
            this.setVisible(true);
            this.setLocationRelativeTo(null);
            // this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        }
    }

    public class mainInterface extends ancestor implements ActionListener, Runnable {
        private JButton all_users = new JButton("管理所有用户");
        private JButton now_users = new JButton("管理当前连接的用户");

        public mainInterface() {
            // GUI
            super("服务器");
            jPanel.add(all_users);
            jPanel.add(now_users);
            this.add(jPanel);

            this.setSize(400, 250);
            jPanel.setLayout(null);
            all_users.setBounds(115, 30, 150, 50);
            now_users.setBounds(90, 120, 200, 50);
            this.setLocationRelativeTo(null);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            all_users.addActionListener(this);
            now_users.addActionListener(this);

            // TCP
            try {
                ss = new ServerSocket(ConstVarible.port);
                new Thread(this).start();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        public void run() {
            try {
                while (true) {
                    s = ss.accept();
                    singleClient sc = new singleClient(s);
                    new Thread(sc).start();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        public void actionPerformed(ActionEvent ae) {
            JButton jButton = (JButton) ae.getSource();
            if (jButton.getText().compareTo("管理所有用户") == 0) {
                new all_users();
            } else if (jButton.getText().compareTo("管理当前连接的用户") == 0) {
                new now_users();
            }
        }
    }

    public class singleClient implements Runnable {
        private Socket s = null;
        private BufferedReader br = null;// save,open,inquire,check account and password
        public PrintStream ps = null;// download,delete
        public String account = null;
        private ArrayList<String> arrayList = null;

        public singleClient(Socket s) {
            this.s = s;
            try {
                br = new BufferedReader(new InputStreamReader(s.getInputStream(),"UTF-8"));
                ps = new PrintStream(s.getOutputStream(),true,"UTF-8");
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

        public void run() {

            try {
                while (true) {
                    String str = new String();
                    try {
                        str = br.readLine();
                    } catch (Exception ex) {
                        // ex.printStackTrace();
                        linkedHashSet.remove(accountString);// 断开连接抛出java.net.SocketException: Connectionreset,移除该用户连接
                        break;
                    }
                    if ("login".compareTo(str) == 0) {
                        account = br.readLine();
                        accountString=account;
                        String password = fileOperation.getPasswordByAccount(account);
                        ps.println(password);
                        linkedHashSet.add(account);
                    }
                    if ("register".compareTo(str) == 0) {
                        account = br.readLine();
                        accountString=account;
                        String password = br.readLine();
                        if (fileOperation.check(account) == false) {
                            fileOperation.register(account, password);
                            ps.println("success");
                        } else {
                            ps.println("failed");
                        }
                        linkedHashSet.add(account);
                    }
                    if ("save".compareTo(str) == 0) {
                        String filename = br.readLine();
                        if (fileOperation.checkNoteName(filename) == true) {
                            ps.println("exist");
                            String str1 = null;
                            try {
                                str1 = br.readLine();
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                            if (str1.compareTo("yes") == 0) {
                                ;// do nothing,接着执行后面的程序
                            } else {
                                new Thread(new singleClient(s)).start();
                                return;
                            }
                        } else {
                            ps.println("not exist");
                        }
                        File notebook = new File(ConstVarible.dataPath + filename);
                        FileWriter fileWriter = new FileWriter(notebook);
                        while (true) {
                            String string = br.readLine();
                            if (string.compareTo(ConstVarible.endFlag) == 0) {
                                break;
                            }
                            fileWriter.write(string + "\n");
                        }
                        fileWriter.close();
                        ps.println("success");
                    }
                    if ("open".compareTo(str) == 0) {
                        account = "str1";
                        arrayList = null;
                        try {
                            account = br.readLine();
                            arrayList = fileOperation.getFileNameByAccount(account);
                            for (int i = 0; i < arrayList.size(); i++) {
                                ps.println(arrayList.get(i));
                            }
                            ps.println(ConstVarible.endFlag);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        int noteSelected = Integer.parseInt(br.readLine());
                        String notename = arrayList.get(noteSelected);
                        File note = new File(notename);
                        FileReader fr = new FileReader(note);
                        BufferedReader br = new BufferedReader(fr);
                        while (true) {
                            String string = br.readLine();
                            if (string == null) {
                                break;
                            }
                            ps.println(string);
                        }
                        ps.println(ConstVarible.endFlag);
                        br.close();
                    }
                    if ("delete".compareTo(str) == 0) {
                        int noteDelete = Integer.parseInt(br.readLine());
                        File file = new File(arrayList.get(noteDelete));
                        String notename = arrayList.get(noteDelete);
                        notename = notename.substring(notename.lastIndexOf("\\") + 1);
                        // notename = notename.substring(notename.indexOf("_") + 1, notename.indexOf("."));
                        // Date date = new Date();
                        // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_mm_dd_hh_mm_ss");
                        // file.renameTo(new File(ConstVarible.dataPath + simpleDateFormat.format(date) + "_" + account
                        //         + "_" + notename + ConstVarible.format_txt));
                        file.renameTo(new File(ConstVarible.deletedPath+notename));
                        if (fileOperation.checkNoteName(account + "_" + notename) == false) {
                            ps.println("success");
                        } else {
                            ps.println("failed");
                        }
                    }
                    if ("inquire".compareTo(str) == 0) {
                        String keyWord = null;
                        try {
                            account = br.readLine();
                            keyWord = br.readLine();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        arrayList = fileOperation.getFileNameByAccount(account);
                        File noteInquire = null;
                        Vector<Vector<String>> data = new Vector<>();
                        for (int i = 0; i < arrayList.size(); i++) {
                            noteInquire = new File(arrayList.get(i));
                            FileReader fileReader = new FileReader(noteInquire);
                            BufferedReader bufferedReader = new BufferedReader(fileReader);
                            String string = new String();
                            int row = 0;// 行数
                            Vector<String> noteVector = new Vector<>();
                            String notename = arrayList.get(i);
                            notename = notename.substring(notename.lastIndexOf("\\") + 1);
                            notename = notename.substring(0, notename.indexOf("."));
                            noteVector.add(notename);
                            try {
                                noteVector.add(String.valueOf(fileOperation.countWordInFile(keyWord, noteInquire)));
                                while (true) {
                                    row++;
                                    string = bufferedReader.readLine();
                                    if (string == null) {
                                        break;
                                    }
                                    int column = string.indexOf(keyWord);
                                    if (column != -1) {
                                        noteVector.add("(" + row + " , " + column + ")");
                                        if (noteVector.size() == 5) {
                                            break;
                                        }
                                    }
                                }
                                data.add(noteVector);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            } finally {
                                try {
                                    bufferedReader.close();
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }
                        }
                        ObjectOutputStream objectOutputStream = new ObjectOutputStream(s.getOutputStream());
                        objectOutputStream.writeObject(data);
                    }
                    if ("exit".compareTo(str) == 0) {

                        String string = br.readLine();
                        linkedHashSet.remove(string);
                    }
                    if ((ConstVarible.startFlag + "makefriends").compareTo(str) == 0) {
                        account = br.readLine();
                        String friendAccount = br.readLine();
                        int res = fileOperation.storeFriendsAccount(account, friendAccount);
                        if (res == 0) {
                            ps.println("该好友账户不存在");
                        } else if (res == 1) {
                            ps.println("您已经添加过该好友");
                        } else if (res == 2) {
                            ps.println("添加成功");
                        } else if (res == 3) {
                            ps.println("添加失败");
                        }
                    }
                    if ((ConstVarible.startFlag + "list").compareTo(str) == 0) {
                        account = br.readLine();
                        ObjectOutputStream objectOutputStream = new ObjectOutputStream(s.getOutputStream());
                        objectOutputStream.writeObject(fileOperation.getfriend(account));
                    }
                    if((ConstVarible.startFlag+"share").compareTo(str)==0){
                        String account=br.readLine();
                        String friendAccount=br.readLine();
                        String noteName=br.readLine();
                        int res=fileOperation.shareNote(account, friendAccount, noteName);
                        if(res==0){
                            ps.println("success");
                        }else{
                            ps.println("failure");
                        }
                    }
                    if((ConstVarible.startFlag+"getshared").compareTo(str)==0){
                        account=br.readLine();
                        ObjectOutputStream oos=new ObjectOutputStream(s.getOutputStream());
                        oos.writeObject(fileOperation.getshared(account));
                    }
                    if((ConstVarible.startFlag+"getsharednote").compareTo(str)==0){
                        account=br.readLine();
                        String notename=br.readLine();
                        String writer=br.readLine();
                        int res=fileOperation.moveSharedTo(writer, notename, account);
                        if(res==0){
                            ps.println("success");
                        }else{
                            ps.println("failure");
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    br.close();
                } catch (Exception ex) {
                    // ex.printStackTrace();
                }
            }
        }
    }

    public class all_users extends ancestor {

        public all_users() {
            super("所有用户");

            columnName.add("用户名称");
            columnName.add("笔记数量");

            data = fileOperation.getClientInfo();
            jTable = new JTable(data, columnName);
            jTable.setPreferredScrollableViewportSize(new Dimension(900, 500));
            Font font = new Font(ConstVarible.font_String, ConstVarible.font_style, ConstVarible.font_size);
            jTable.setFont(font);
            jTable.setFillsViewportHeight(true);
            jScrollPane = new JScrollPane(jTable);
            jPanel.add(jScrollPane);
            this.add(jPanel);
            this.setSize(1000, 700);
            this.setLocationRelativeTo(null);
        }
    }

    public class now_users extends ancestor {

        public now_users() {
            super("当前连接的用户");
            columnName.add("用户名称");
            Iterator<String> iterator = linkedHashSet.iterator();
            while (iterator.hasNext()) {
                Vector<String> vector = new Vector<>();
                vector.add(iterator.next());
                data.add(vector);
            }
            jTable = new JTable(data, columnName);
            jTable.setPreferredScrollableViewportSize(new Dimension(900, 500));
            Font font = new Font(ConstVarible.font_String, ConstVarible.font_style, ConstVarible.font_size);
            jTable.setFont(font);
            jTable.setFillsViewportHeight(true);
            jScrollPane = new JScrollPane(jTable);
            jPanel.add(jScrollPane);
            this.add(jPanel);
            this.setSize(1000, 700);
            this.setLocationRelativeTo(null);
        }
    }

    public static void main(String[] args) {
        server s = new server();
        s.new mainInterface();
    }
}

文件操作fileOperation

package code;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;

import javax.swing.JOptionPane;

public class fileOperation {
    private static Properties pps;
    static {
        pps = new Properties();
        FileReader reader = null;
        try {
            File file=new File(ConstVarible.dataPath + "account.inc");
            if(file.exists()==false){
                file.createNewFile();
            }
            reader = new FileReader(file);
            pps.load(reader);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "文件操作异常1");
            System.exit(0);
        } finally {
            try {
                reader.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void register(String nickname, String password) {
        pps.setProperty(nickname, password);
        PrintStream ps = null;
        try {
            ps = new PrintStream(ConstVarible.dataPath + "account.inc");
            pps.list(ps);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "文件操作异常2");
            System.exit(0);
        } finally {
            try {
                ps.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public static String getPasswordByAccount(String account) {
        String password = pps.getProperty(account);
        return password;
    }

    public static boolean check(String str) {// 没找到返回false,找到返回true
        if (pps.getProperty(str) == null) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean checkNoteName(String str) {// filename已存在返回true,否则false
        File file = new File(ConstVarible.dataPath + str);
        if (file.exists() == true) {
            return true;
        } else {
            return false;
        }
    }

    public static ArrayList<String> getFileNameByAccount(String account) {
        File file = new File(ConstVarible.dataFile);
        File[] files = file.listFiles();
        ArrayList<String> arrayList = new ArrayList<String>();
        for (File f : files) {
            String filename = f.getAbsolutePath();
            // System.out.println(filename);
            if (filename.startsWith(ConstVarible.dataPath+account + "_")) {
                arrayList.add(filename);
            }
        }
        return arrayList;
    }

    public static int countWordInFile(String word,File file)throws Exception{
        FileInputStream fis=new FileInputStream(file);
        byte[] data=new byte[(int)file.length()];
        fis.read(data);
        fis.close();
        String msg=new String(data);
        String aft=msg.replace(word, "");
        return (msg.length()-aft.length())/word.length();
    }

    public static Vector<Vector<String>> getClientInfo(){
        File file=new File(ConstVarible.dataFile);
        File[] files=file.listFiles();
        Vector<Vector<String>> data=new Vector<>();
        TreeMap<String,Integer> treeMap=new TreeMap<>();
        for(File f:files){
            String filename=f.getName();
            String str=filename.replace("_", "");
            int numOf_=(filename.length()-str.length())/"_".length();
            if(numOf_==1){
                if(treeMap.containsKey(filename)){
                    treeMap.put(filename.substring(0,filename.indexOf("_")),treeMap.get(filename)+1);
                }
                else{
                    treeMap.put(filename.substring(0,filename.indexOf("_")),1);
                }
            }
        }
        Set keySet=treeMap.keySet();
        for(Object key:keySet){
            Vector<String> row=new Vector<>();
            // System.out.println(key+" "+treeMap.get(key));
            row.add(String.valueOf(key));
            row.add(String.valueOf(treeMap.get(key)));
            data.add(row);
        }
        return data;
    }

    public static Vector<Vector<String>> getfriend(String account) {
        File file = new File(ConstVarible.friendsPath+account);
        if(file.exists()==false)return null;
        Vector<Vector<String>> data = new Vector<>();
        try{
            FileReader fileReader=new FileReader(file);
            BufferedReader bufferedReader=new BufferedReader(fileReader);
            while(true){
                String string=bufferedReader.readLine();
                // System.out.println(string);
                if(string==null)break;
                Vector<String> row=new Vector<>();
                row.add(string);
                data.add(row);
            }
            bufferedReader.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return data;
    }

    public static int storeFriendsAccount(String account, String friendAccount) {
        if (check(friendAccount) == false) {// 先检查好友账户是否存在
            return 0;
        } else {
            File file = new File(ConstVarible.friendsPath + account);
            try {
                if (file.exists() == false) {//检查文件是否存在
                    file.createNewFile();
                }
                if(countWordInFile(friendAccount, file)==1){//检查是否已经添加过该好友
                    return 1;
                }
                FileWriter fw=new FileWriter(file,true);
                fw.append(friendAccount+"\n");
                fw.close();
                storeFriendsAccount(friendAccount, account);//互为好友
                return 2;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return 3;
        }
    }

    public static int shareNote(String account,String friendAccount,String noteName){
        if(checkNoteName(account+"_"+noteName+ConstVarible.format_txt)==false)return -1;
        File folder=new File(ConstVarible.dataPath+account+"ShareWith"+friendAccount);
        if(folder.exists()==false){
            folder.mkdirs();
        }
        File sharedNote=new File(ConstVarible.dataPath+account+"_"+noteName+ConstVarible.format_txt);
        try{
            Files.copy(sharedNote.toPath(),new File(ConstVarible.dataPath+account+"ShareWith"+friendAccount+"\\"+account+"_"+noteName+ConstVarible.format_txt).toPath());
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return 0;
    }

    public static Vector<Vector<String>> getshared(String account){
        File file = new File(ConstVarible.dataFile);
        File[] files = file.listFiles();
        Vector<Vector<String>> data=new Vector<>();
        //遍历所有文件,查看分享
        for (File f : files) {
            if(f.isDirectory()==true && f.getName().endsWith("ShareWith"+account)==true){
                File[] sonfiles=f.listFiles();
                for(File f2:sonfiles){
                    String filename=f2.getName();
                    Vector<String> row=new Vector<>();
                    row.add(filename.substring(filename.indexOf("_")+1,filename.indexOf(".")));
                    row.add(filename.substring(0,filename.indexOf("_")));
                    data.add(row);
                }
            }
        }
        return data;
    }

    public static int moveSharedTo(String writer,String notename,String account){
        File file = new File(ConstVarible.dataFile);
        File[] files = file.listFiles();
        //遍历所有文件
        for (File f : files) {
            if(f.isDirectory()==true && f.getName().endsWith("ShareWith"+account)==true){
                File[] sonfiles=f.listFiles();
                for(File f2:sonfiles){
                    String filename=f2.getName();
                    if(filename.compareTo(writer+"_"+notename+ConstVarible.format_txt)==0){
                        f2.renameTo(new File(ConstVarible.dataPath+account+"_"+notename+ConstVarible.format_txt));
                    }
                }
            }
        }
        return 0;
    }
}

常量ConstVarible

package code;
import java.awt.Font;
public class ConstVarible {
    public static final int port=9999;
    public static final String startFlag="+_)(*&^%$#@!~";
    public static final String endFlag="!@#$%^&*()";
    public static final String friendsPath="C:\\Users\\mashed potato\\Desktop\\vscode\\.vscode\\NOTA_server\\src\\data\\friends\\";
    public static final String deletedPath="C:\\Users\\mashed potato\\Desktop\\vscode\\.vscode\\NOTA_server\\src\\data\\deleted_files\\";
    public static final String dataPath="C:\\Users\\mashed potato\\Desktop\\vscode\\.vscode\\NOTA_server\\src\\data\\";
    public static final String dataFile="C:\\Users\\mashed potato\\Desktop\\vscode\\.vscode\\NOTA_server\\src\\data";
    public static final String format_txt=".txt";
    public static final String font_String="楷体_GB2312";
    public static final int font_style=Font.PLAIN;
    public static final int font_size=15;
}

客户端client

package code;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;

import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Vector;
import java.awt.Font;

public class client {

    public class ancestor extends JFrame {
        protected JPanel jPanel = new JPanel();
        protected Socket s = null;
        protected OutputStream os = null;
        protected PrintStream ps = null;
        protected InputStream is = null;
        protected BufferedReader br = null;
        protected String title = null;

        public ancestor(String str) {
            super(str);
            title = str;

            this.setVisible(true);
            this.setLocationRelativeTo(null);
            this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            this.setResizable(false);

            try {
                s = new Socket(ConstVarible.address_home_wifi, ConstVarible.port);
                os = s.getOutputStream();
                ps = new PrintStream(os, true, "UTF-8");
                is = s.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public class login extends ancestor implements ActionListener, FocusListener {// 登录界面
        private GridLayout gridLayout = new GridLayout(3, 2, 20, 20);
        private JLabel label_name = new JLabel("账号");
        private JLabel label_password = new JLabel("密码");
        private JTextField input_name = new JTextField("输入账号");
        private JPasswordField input_password = new JPasswordField("输入密码");
        private JButton registerButton = new JButton("去注册");
        private JButton loginButton = new JButton("登录");

        public login() {
            super("登录界面");
            jPanel.setLayout(gridLayout);
            jPanel.add(label_name);
            jPanel.add(input_name);
            jPanel.add(label_password);
            jPanel.add(input_password);
            jPanel.add(loginButton);
            jPanel.add(registerButton);
            this.add(jPanel);

            this.setSize(400, 300);
            this.setLocationRelativeTo(null);

            registerButton.addActionListener(this);
            loginButton.addActionListener(this);
            input_name.addFocusListener(this);
            input_password.addFocusListener(this);
            input_password.addActionListener(this);
        }

        public void actionPerformed(ActionEvent e) {
            JButton jButton = new JButton("jButton");
            try {
                jButton = (JButton) e.getSource();
            } catch (Exception ex) {
                log();
                return;
            }

            if (jButton.getText().compareTo("去注册") == 0) {
                new client().new register();
                this.dispose();
            } else {
                log();
            }
        }

        public void log() {
            String realPassword = null;
            try {
                ps.println("login");
                ps.println(input_name.getText());
                // System.out.println("waiting");
                realPassword = br.readLine();
                // System.out.println("waiting2");
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    br.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (realPassword.compareTo(String.valueOf(input_password.getPassword())) == 0) {
                JOptionPane.showMessageDialog(null, "登录成功");
                new client().new mainInterface(input_name.getText());
                this.dispose();
            } else {
                JOptionPane.showMessageDialog(null, "账号不存在或密码错误");
                new client().new login();
                this.dispose();
            }
        }

        public void focusGained(FocusEvent fe) {
            if (input_name.isFocusOwner() == true) {
                input_name.setText("");
            }
            if (input_password.isFocusOwner() == true) {
                input_password.setText("");
            }

        }

        public void focusLost(FocusEvent fe) {
            if (input_name.isFocusOwner() == false) {
                // input_name.setText("输入账号");
            }
            if (input_password.isFocusOwner() == false) {
                // input_password.setText("输入密码");
            }

        }
    }

    public class register extends ancestor implements ActionListener, FocusListener {
        private GridLayout gridLayout = new GridLayout(4, 2, 20, 20);
        private JLabel label_name = new JLabel("账号");
        private JLabel label_password = new JLabel("密码");
        private JLabel label_password_again = new JLabel("确认密码");
        private JTextField input_name = new JTextField("输入账号");
        private JPasswordField input_password = new JPasswordField("输入密码");
        private JPasswordField input_password_again = new JPasswordField("重复密码");
        private JButton registerButton = new JButton("注册");
        private JButton cancelButton = new JButton("取消");

        public register() {
            super("注册界面");
            input_name.addFocusListener(this);
            input_password.addFocusListener(this);
            input_password_again.addFocusListener(this);
            jPanel.setLayout(gridLayout);
            jPanel.add(label_name);
            jPanel.add(input_name);
            jPanel.add(label_password);
            jPanel.add(input_password);
            jPanel.add(label_password_again);
            jPanel.add(input_password_again);
            jPanel.add(registerButton);
            jPanel.add(cancelButton);
            this.add(jPanel);
            this.setSize(500, 400);
            this.setLocationRelativeTo(null);

            registerButton.addActionListener(this);
            cancelButton.addActionListener(this);
        }

        public void actionPerformed(ActionEvent e) {
            JButton jButton = (JButton) e.getSource();
            if (jButton.getText().compareTo("注册") == 0) {
                if (String.valueOf(input_password.getPassword())
                        .compareTo(String.valueOf(input_password_again.getPassword())) == 0) {
                    try {
                        os = s.getOutputStream();
                        ps = new PrintStream(os, true, "UTF-8");
                        ps.println("register");
                        ps.println(input_name.getText());
                        ps.println(String.valueOf(input_password.getPassword()));

                        is = s.getInputStream();
                        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                        if (br.readLine().compareTo("success") == 0) {
                            JOptionPane.showMessageDialog(this, "注册成功");
                            new client().new mainInterface(input_name.getText());
                            this.dispose();
                        } else {
                            JOptionPane.showMessageDialog(this, "此账号已存在");
                            new client().new register();
                            this.dispose();
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    } finally {
                        try {
                            br.close();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                    }
                } else {
                    JOptionPane.showMessageDialog(null, "密码与确认密码不一致,请重新输入");
                }

            } else if (jButton.getText().compareTo("取消") == 0) {
                new client().new login();
                this.dispose();
            }
        }

        public void focusGained(FocusEvent fe) {
            if (input_name.isFocusOwner() == true) {
                input_name.setText("");
            }
            if (input_password.isFocusOwner() == true) {
                input_password.setText("");
            }
            if (input_password_again.isFocusOwner() == true) {
                input_password_again.setText("");
            }
        }

        public void focusLost(FocusEvent fe) {
        }
    }

    public class mainInterface extends ancestor implements ActionListener {
        protected JMenuBar jMenuBar = new JMenuBar();
        protected JMenu file = new JMenu("文件");
        protected JMenuItem newNote = new JMenuItem("新建笔记");
        protected JMenuItem saveNote = new JMenuItem("保存笔记");
        protected JMenuItem openNote = new JMenuItem("打开笔记");
        protected JMenuItem deleteNote = new JMenuItem("删除笔记");
        protected JMenuItem inquireNote = new JMenuItem("查询笔记");
        protected JMenuItem downloadNote = new JMenuItem("下载笔记");
        protected JMenu friends = new JMenu("好友");
        protected JMenuItem makefriends = new JMenuItem("添加好友");
        protected JMenuItem myfriends = new JMenuItem("我的好友");
        protected JMenuItem shareNote = new JMenuItem("分享笔记");
        protected JMenuItem getSharedNote = new JMenuItem("获得笔记");
        protected JMenu accountJMenu = new JMenu("我的");
        // protected JMenuItem modifiyInfo = new JMenuItem("修改账户信息");
        protected JMenuItem exitItem = new JMenuItem("退出");
        protected JTextArea newJTextArea = new JTextArea(30, 60);
        protected JScrollPane newJScrollPane = new JScrollPane(newJTextArea);
        protected String title = null;

        public mainInterface(String str) {
            super(str + "的笔记");
            title = str;
            newNote.addActionListener(this);
            saveNote.addActionListener(this);
            openNote.addActionListener(this);
            deleteNote.addActionListener(this);
            inquireNote.addActionListener(this);
            downloadNote.addActionListener(this);
            makefriends.addActionListener(this);
            myfriends.addActionListener(this);
            shareNote.addActionListener(this);
            getSharedNote.addActionListener(this);
            // modifiyInfo.addActionListener(this);
            exitItem.addActionListener(this);
            jPanel.add(jMenuBar);
            jMenuBar.add(file);
            jMenuBar.add(friends);
            jMenuBar.add(accountJMenu);
            file.add(newNote);
            file.add(saveNote);
            file.add(openNote);
            file.add(deleteNote);
            file.add(inquireNote);
            file.add(downloadNote);
            friends.add(makefriends);
            friends.add(myfriends);
            friends.add(shareNote);
            friends.add(getSharedNote);
            // accountJMenu.add(modifiyInfo);
            accountJMenu.add(exitItem);

            jPanel.setLayout(null);
            this.add(jPanel);
            this.setSize(1000, 700);
            jMenuBar.setBounds(430, 20, 120, 30);
            this.setLocationRelativeTo(null);
        }

        public void actionPerformed(ActionEvent ae) {
            JMenuItem jMenuItem = (JMenuItem) ae.getSource();
            String string = jMenuItem.getText();
            switch (string) {
                case "新建笔记":
                    new newNote(title);
                    break;
                case "保存笔记":
                    new saveNote(title, this);
                    break;
                case "打开笔记":
                    new openNote(title);
                    break;
                case "删除笔记":
                    new deleteNote(title);
                    break;
                case "查询笔记":
                    new inquireNote(title);
                    break;
                case "下载笔记":
                    new downloadNote(title);
                    break;
                case "退出":
                    ps.println("exit");
                    ps.println(title);
                    System.exit(0);
                    break;
                case "添加好友":
                    new makefriend(title);
                    break;
                case "我的好友":
                    new listfriend(title);
                    break;
                case "分享笔记":
                    new shareNote(title);
                    break;
                case "获得笔记":
                    new getSharedNote(title);
                    break;
            }
        }
    }

    public class newNote extends mainInterface {
        public newNote(String str) {
            super(str);
            this.setTitle(str + "的新建笔记");
            jPanel.add(newJScrollPane);
            this.add(jPanel);

            newJScrollPane.setBounds(90, 80, 800, 520);
            Font jTextAreaFont = new Font("楷体_GB2312", Font.PLAIN, 15);
            newJTextArea.setFont(jTextAreaFont);
            // newJTextArea.setLineWrap(true);
        }
    }

    public class saveNote extends ancestor implements ActionListener {
        private JLabel nameJLabel = new JLabel("笔记名称");
        private JTextField nameJTextField = new JTextField();
        private JButton saveButton = new JButton("保存");
        private JButton cancelButton = new JButton("取消");
        private GridLayout gridLayout = new GridLayout(2, 2, 20, 20);
        mainInterface anotherInterface = null;

        public saveNote(String str, mainInterface jframe) {
            super(str);
            anotherInterface = jframe;
            this.setTitle(str + "的保存笔记");
            this.setVisible(true);
            this.setSize(300, 170);
            jPanel.setLayout(gridLayout);
            this.setLocationRelativeTo(null);

            jPanel.add(nameJLabel);
            jPanel.add(nameJTextField);
            jPanel.add(saveButton);
            jPanel.add(cancelButton);
            this.add(jPanel);

            saveButton.addActionListener(this);
            cancelButton.addActionListener(this);
        }

        public void actionPerformed(ActionEvent ae) {
            JButton jButton = (JButton) ae.getSource();
            if (jButton.getText().compareTo("保存") == 0) {
                String account = anotherInterface.title;
                ps.println("save");
                ps.println(account + "_" + nameJTextField.getText() + ".txt");// 用户名+name
                String str = "str";
                try {
                    str = br.readLine();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                if (str.compareTo("exist") == 0) {
                    int isCover = JOptionPane.showConfirmDialog(this, "该笔记本名称已存在,继续保存将覆盖原有笔记本,是否继续?");
                    if (isCover == 0) {// 确认覆盖,接着执行后面的程序
                        ps.println("yes");
                    } else {// 否则,重新输入
                        ps.println("no");
                        return;
                    }
                }

                ps.println(anotherInterface.newJTextArea.getText());
                ps.println(ConstVarible.endFlag);
                try {
                    String str1 = br.readLine();
                    if (str1.compareTo("success") == 0) {
                        JOptionPane.showMessageDialog(this, "保存成功");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                this.dispose();

            } else if (jButton.getText().compareTo("取消") == 0) {
                this.dispose();
            }
        }
    }

    public class openNote extends mainInterface implements ListSelectionListener {
        protected JTable jTable = null;
        protected JScrollPane jScrollPane = null;
        protected Vector<Vector<String>> data = new Vector<>();
        protected Vector<String> columnName = new Vector<>();

        public openNote(String str) {
            super(str);
            this.setTitle(str + "的打开笔记");

            ps.println("open");
            ps.println(str);
            String notename = null;
            try {
                while (true) {
                    notename = br.readLine();
                    if (notename.compareTo(ConstVarible.endFlag) == 0) {
                        break;
                    }
                    notename = notename.substring(notename.lastIndexOf("\\") + 1);
                    notename = notename.substring(notename.indexOf("_") + 1, notename.indexOf("."));
                    Vector<String> row = new Vector<>();
                    row.add(notename);
                    data.add(row);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            FlowLayout flowLayout = new FlowLayout();
            jPanel.setLayout(flowLayout);

            columnName.add("笔记名称");
            jTable = new JTable(data, columnName) {
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
            jTable.setPreferredScrollableViewportSize(new Dimension(900, 500));
            Font font = new Font(ConstVarible.font_String, ConstVarible.font_style, ConstVarible.font_size);
            jTable.setFont(font);
            jTable.getSelectionModel().addListSelectionListener(this);
            jTable.setFillsViewportHeight(true);
            DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
            defaultTableCellRenderer.setHorizontalAlignment(JLabel.CENTER);
            jTable.setDefaultRenderer(Object.class, defaultTableCellRenderer);
            jScrollPane = new JScrollPane(jTable);
            jPanel.add(jScrollPane);
            this.add(jPanel);
        }

        public void valueChanged(ListSelectionEvent le) {
            int row = jTable.getSelectedRow();
            if (le.getValueIsAdjusting() == false) {
                ps.println(row);
                newNote opennote = new newNote(title);
                opennote.setTitle(title + "的笔记:" + jTable.getModel().getValueAt(row, 0));
                this.dispose();
                try {
                    while (true) {
                        String string = br.readLine();
                        if (string.compareTo(ConstVarible.endFlag) == 0) {
                            break;
                        }
                        opennote.newJTextArea.append(string + "\n");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        }
    }

    public class deleteNote extends openNote {
        public deleteNote(String str) {
            super(str);
            this.setTitle(str + "的删除笔记");
        }

        public void valueChanged(ListSelectionEvent le) {
            int row = jTable.getSelectedRow();
            if (le.getValueIsAdjusting() == false) {
                ps.println(row);
                newNote opennote = new newNote(title);
                opennote.setTitle(title + "的笔记:" + jTable.getModel().getValueAt(row, 0));
                try {
                    while (true) {
                        String string = br.readLine();
                        if (string.compareTo(ConstVarible.endFlag) == 0) {
                            break;
                        }
                        opennote.newJTextArea.append(string + "\n");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                int isDeleted = JOptionPane.showConfirmDialog(opennote, "是否删除该笔记?");
                if (isDeleted == 0) {
                    ps.println("delete");
                    ps.println(row);
                    try {
                        if (br.readLine().compareTo("success") == 0) {
                            opennote.newJTextArea.setText("");
                            opennote.dispose();
                            this.dispose();
                            JOptionPane.showMessageDialog(this, "删除成功");
                        } else {
                            JOptionPane.showMessageDialog(this, "删除失败");
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }
            }
        }
    }

    public class inquireNote extends mainInterface {
        protected JTable jTable = null;
        protected JScrollPane jScrollPane = null;

        public inquireNote(String str) {
            super(str);
            this.setTitle(str + "的查询笔记");
            this.dispose();
            String keyWord = JOptionPane.showInputDialog(this, "请输入您想要查询的关键词");
            if (keyWord == null) {
                return;
            }
            if (keyWord.compareTo("") == 0) {
                JOptionPane.showMessageDialog(this, "未输入任何内容");
                return;
            }
            this.setVisible(true);

            ps.println("inquire");
            ps.println(title);
            ps.println(keyWord);

            Vector<Vector<String>> data = null;
            ObjectInputStream objectInputStream = null;
            try {
                objectInputStream = new ObjectInputStream(is);
                data = (Vector<Vector<String>>) objectInputStream.readObject();
            } catch (Exception ex) {
                System.out.println("objecetInputStream");
                ex.printStackTrace();
            }

            FlowLayout flowLayout = new FlowLayout();
            jPanel.setLayout(flowLayout);

            Vector<String> columnName = new Vector<>();
            columnName.add("笔记名称");
            columnName.add("出现次数");
            for (int i = 1; i <= 5; i++) {
                columnName.add("第" + i + "行次出现在(行,列)");
            }

            jTable = new JTable(data, columnName) {
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
            jTable.setPreferredScrollableViewportSize(new Dimension(900, 500));
            Font font = new Font("楷体_GB2312", Font.PLAIN, 15);
            jTable.setFont(font);
            DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
            defaultTableCellRenderer.setHorizontalAlignment(JLabel.CENTER);
            jTable.setDefaultRenderer(Object.class, defaultTableCellRenderer);
            jTable.setFillsViewportHeight(true);
            jScrollPane = new JScrollPane(jTable);
            jPanel.add(jScrollPane);
            this.add(jPanel);
            this.validate();
        }

    }

    public class downloadNote extends openNote {
        int row = jTable.getSelectedRow();
        JFileChooser jFileChooser = null;
        File noteDownload = null;
        FileWriter fileWriter = null;

        public downloadNote(String str) {
            super(str);
            this.setTitle(str + "的下载笔记");
        }

        public void valueChanged(ListSelectionEvent le) {
            int row = jTable.getSelectedRow();
            if (le.getValueIsAdjusting() == false) {
                jFileChooser = new JFileChooser();
                jFileChooser.setDialogTitle("选择下载路径");
                jFileChooser.setApproveButtonText("选择");
                jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int returnVal = jFileChooser.showOpenDialog(this);
                String noteDownloadPath = null;
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    noteDownloadPath = jFileChooser.getSelectedFile().getAbsolutePath();
                }
                String notename = JOptionPane.showInputDialog(this, "请输入笔记名称");
                noteDownload = new File(noteDownloadPath + "\\" + notename + ConstVarible.format_txt);
                try {
                    fileWriter = new FileWriter(noteDownload);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                ps.println(row);
                try {
                    while (true) {
                        String string = br.readLine();
                        if (string.compareTo(ConstVarible.endFlag) == 0) {
                            break;
                        }
                        fileWriter.write(string + "\n");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(this, "下载失败");
                    return;
                } finally {
                    try {
                        fileWriter.close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }
                JOptionPane.showMessageDialog(this, "下载成功");
                this.dispose();
            }
        }
    }

    public class makefriend extends ancestor {
        public makefriend(String account) {
            super("交友");
            this.setVisible(false);

            String friendAccount = JOptionPane.showInputDialog(this, "请输入好友账号");
            if (friendAccount == null || friendAccount.compareTo("") == 0) {
                return;
            } else {
                ps.println(ConstVarible.startFlag + "makefriends");
                ps.println(account);
                ps.println(friendAccount);
                // JOptionPane.showMessageDialog(this, "hh");
                try {
                    JOptionPane.showMessageDialog(this, br.readLine());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public class listfriend extends ancestor {
        protected JTable jTable = null;
        protected JScrollPane jScrollPane = null;
        protected Vector<Vector<String>> data = new Vector<>();
        protected Vector<String> columnName = new Vector<>();

        public listfriend(String account) {
            super(account);
            this.setTitle("好友列表");

            ps.println(ConstVarible.startFlag + "list");
            ps.println(account);
            ObjectInputStream objectInputStream = null;
            try {
                objectInputStream = new ObjectInputStream(is);
                data = (Vector<Vector<String>>) objectInputStream.readObject();
            } catch (Exception ex) {
                System.out.println("objecetInputStream");
                ex.printStackTrace();
            }
            FlowLayout flowLayout = new FlowLayout();
            jPanel.setLayout(flowLayout);
            columnName.add("好友列表");
            jTable = new JTable(data, columnName) {
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
            jTable.setPreferredScrollableViewportSize(new Dimension(600, 450));
            Font font = new Font(ConstVarible.font_String, ConstVarible.font_style, ConstVarible.font_size);
            jTable.setFont(font);
            jTable.setFillsViewportHeight(true);
            DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
            defaultTableCellRenderer.setHorizontalAlignment(JLabel.CENTER);
            jTable.setDefaultRenderer(Object.class, defaultTableCellRenderer);
            jScrollPane = new JScrollPane(jTable);
            jPanel.add(jScrollPane);
            this.add(jPanel);
            this.setSize(700, 500);
            this.setLocationRelativeTo(null);
        }
    }

    public class shareNote extends openNote {
        public shareNote(String account) {
            super(account);
            this.setTitle(account + "的分享笔记");
        }

        public void valueChanged(ListSelectionEvent le) {
            int row = jTable.getSelectedRow();
            if (le.getValueIsAdjusting() == false) {
                ps.println(row);
                newNote opennote = new newNote(title);
                opennote.setTitle(title + "的笔记:" + jTable.getModel().getValueAt(row, 0));
                try {
                    while (true) {
                        String string = br.readLine();
                        if (string.compareTo(ConstVarible.endFlag) == 0) {
                            break;
                        }
                        opennote.newJTextArea.append(string + "\n");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                String friendAccount = JOptionPane.showInputDialog(opennote, "请输入您想要分享该笔记的好友账号");
                if (friendAccount != null && friendAccount.compareTo("") != 0) {
                    ps.println(ConstVarible.startFlag + "share");
                    ps.println(title);
                    ps.println(friendAccount);
                    ps.println(data.get(row).get(0));
                    try {
                        String str = br.readLine();
                        if (str.compareTo("success") == 0) {
                            JOptionPane.showMessageDialog(this, "分享成功,等待好友接受");
                        } else {
                            JOptionPane.showMessageDialog(this, "分享失败");
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }

    public class getSharedNote extends mainInterface implements ListSelectionListener {
        protected JTable jTable = null;
        protected JScrollPane jScrollPane = null;
        protected Vector<Vector<String>> data = new Vector<>();
        protected Vector<String> columnName = new Vector<>();

        public getSharedNote(String account) {
            super(account);
            this.setTitle("获得笔记");

            // 获取表格数据
            columnName.add("笔记名称");
            columnName.add("分享者");

            ps.println(ConstVarible.startFlag + "getshared");
            ps.println(account);
            try {
                ObjectInputStream ois = new ObjectInputStream(is);
                data = (Vector<Vector<String>>) ois.readObject();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            // 排版
            FlowLayout flowLayout = new FlowLayout();
            jPanel.setLayout(flowLayout);
            jTable = new JTable(data, columnName) {
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
            jTable.setPreferredScrollableViewportSize(new Dimension(600, 450));
            Font font = new Font(ConstVarible.font_String, ConstVarible.font_style, ConstVarible.font_size);
            jTable.setFont(font);
            jTable.getSelectionModel().addListSelectionListener(this);
            jTable.setFillsViewportHeight(true);
            DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer();
            defaultTableCellRenderer.setHorizontalAlignment(JLabel.CENTER);
            jTable.setDefaultRenderer(Object.class, defaultTableCellRenderer);
            jScrollPane = new JScrollPane(jTable);
            jPanel.add(jScrollPane);
            this.add(jPanel);
            this.setSize(700, 500);
            this.setLocationRelativeTo(null);
        }

        public void valueChanged(ListSelectionEvent le) {
            int row = jTable.getSelectedRow();
            if (le.getValueIsAdjusting() == false) {
                int res = JOptionPane.showConfirmDialog(this, "是否接受该笔记");
                if (res == JOptionPane.YES_OPTION) {
                    ps.println(ConstVarible.startFlag + "getsharednote");
                    ps.println(title);
                    ps.println(data.get(row).get(0));
                    ps.println(data.get(row).get(1));
                    try {
                        if (br.readLine().compareTo("success") == 0) {
                            JOptionPane.showMessageDialog(this, "接收成功");
                        } else {
                            JOptionPane.showMessageDialog(this, "接收失败");
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }

                }
            }
        }
    }

    public static void main(String[] args) {
        client c = new client();
        login l = c.new login();
    }
}

常量ConstVarlble

package code;
import java.awt.Font;

public class ConstVarible {
    // public static final String address_home_wifi="192.168.0.100";
    public static final String address_home_wifi="106.53.197.20";//云服务器
    public static final int port=9999;
    public static final String startFlag="+_)(*&^%$#@!~";
    public static final String endFlag="!@#$%^&*()";
    public static final String format_txt=".txt";
    public static final String font_String="楷体_GB2312";
    public static final int font_style=Font.PLAIN;
    public static final int font_size=15;
}

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值