Skip to content
Snippets Groups Projects
Select Git revision
  • 767d645bfad1a8dd84a7de7980f86b84a5b0202a
  • main default protected
  • section4
  • save_state
  • section2
  • section1
6 results

HelloController.java

Blame
  • HelloController.java 15.66 KiB
    package com.example.tpfx;
    
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.fxml.FXML;
    import javafx.scene.control.*;
    
    import java.io.*;
    import java.util.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class HelloController {
        static ArrayList<Contact> contactArray = new ArrayList<>();
        int selectedID = 0; //Save the id of the selected item in the list view
        boolean imported = false; //Used to know whenever we should enable or disable button save/edit
        ObservableList<String> ctType = FXCollections.observableArrayList("Friend", "Family", "Professional");
        //Fx fields
        @FXML
        private TextField txtFirst;
        @FXML
        private TextField txtSearch;
        @FXML
        private TextField txtLast;
        @FXML
        private TextField txtAdd;
        @FXML
        private TextField txtPhone;
        @FXML
        private TextField txtEmail;
        @FXML
        private TextField txtSocial;
        @FXML
        private TextField txtJob;
        @FXML
        private TextField txtOther;
        @FXML
        private Label lblOther;
        @FXML
        private Button btnAdd;
        @FXML
        private Button btnDelete;
        @FXML
        private Button btnEdit;
        @FXML
        private ListView LstCt;
        @FXML
        private ComboBox cbxType;
    
        //Fx functions
        /**
         * Form start up. Hide and Disable unwanted component
         */
        @FXML
        protected void initialize() {
            cbxType.setValue("Friend");
            cbxType.setItems(ctType);
            lblOther.setVisible(false);
            txtOther.setVisible(false);
            btnEdit.setDisable(true);
            btnDelete.setDisable(true);
            btnAdd.setDisable(true);
        }
        /**
         * Redirect the addition of a contact to the correct methode
         */
        @FXML
        protected void AddCt() {
            //enhanced switch, doesn't need break
            switch (cbxType.getValue().toString()){ //Use the combo box value
                case "Friend" -> AddPal();
                case "Family" -> AddFam();
                case "Professional" -> AddPro();
            }
        }
        /**
         * Check the value of the Contact Type ComboBox and change the form accordingly
         */
        @FXML
        protected void ChangeType(){
            switch (cbxType.getValue().toString()){
                case "Friend":
                    lblOther.setVisible(false);
                    txtOther.setVisible(false);
                    break;
                case "Family":
                    lblOther.setVisible(true);
                    lblOther.setText("Relation");
                    txtOther.setVisible(true);
                    break;
                case "Professional":
                    lblOther.setVisible(true);
                    lblOther.setText("Work Place");
                    txtOther.setVisible(true);
                    break;
            }
        }
        /**
         * Import a CSV file and convert it into a list of Contacts
         */
        @FXML
        protected void ImportCt() {
            LstCt.getItems().clear();
            contactArray.clear();
            try{
                BufferedReader reader = new BufferedReader(new FileReader("contact_save.csv"));
                String line;
                int checker = 0;
                while((line = reader.readLine()) != null){
                    switch (line){
                        case "Friend":
                            checker = 1; //checker is used to know which type of contact it is to it to the list
                            break;
                        case "Family":
                            checker = 2;
                            break;
                        case "Professional":
                            checker = 3;
                            break;
                        default:
                            List<String> str_array = SplitLine(line, "/");
                            AddContactToList(str_array, checker);
                            checker = 0;
                            break;
                    }
                }
                reader.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
        /**
         * Svae the Contact List into a CSV file
         */
        @FXML
        protected void ExportCt() {
            try{
                BufferedWriter writer = new BufferedWriter(new FileWriter("contact_save.csv"));
                for (Contact c: contactArray){
                    List<String> str_array = SplitLine(c.toString(), " - ");
                    writer.write(c.getType() + "\n"); //First line is contact type (for easier usage during import)
                    writer.write(str_array.get(0) + "/");
                    writer.write(str_array.get(1) + "/");
                    writer.write(str_array.get(2) + "/");
                    writer.write(str_array.get(3) + "/");
                    writer.write(str_array.get(4) + "/");
                    writer.write(str_array.get(5) + "/");
                    writer.write(str_array.get(6) + "/");
                    writer.write(str_array.get(7));
                    if(c instanceof Family || c instanceof Professional){
                        writer.write("/" + str_array.get(8) + "\n");
                    } else{
                        writer.write("/" + "\n");
                    }
                }
                writer.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
        /**
         * Search for a contact based on the First Name
         */
        @FXML
        protected void Search() {
            Pattern pat = Pattern.compile(txtSearch.getText());
            LstCt.getItems().clear();
            for(Contact c: contactArray){
                for(String n: c.getFirstName()){
                    Matcher match = pat.matcher(n);
                    if(match.find()){
                        LstCt.getItems().add(c);
                    }
                }
            }
        }
        /**
         * Get contact info and put them in the text fields
         */
        @FXML
        protected void Selected() {
            lblOther.setVisible(true);
            btnDelete.setDisable(false);
            btnEdit.setDisable(false);
            List<String> data = SplitLine(LstCt.getSelectionModel().getSelectedItem().toString(), " - ");
    
            lblOther.setVisible(true);
            lblOther.setText(data.get(1));
            selectedID = Integer.parseInt(data.get(0));
            txtFirst.setText(data.get(1));
            txtLast.setText(data.get(2));
            txtAdd.setText(data.get(3));
            txtPhone.setText(data.get(4));
            txtEmail.setText(data.get(5));
            txtSocial.setText(data.get(6));
            txtJob.setText(data.get(7));
    
            //Family and professional have one more arguments
            if(data.size() > 8){
                txtOther.setVisible(true);
                lblOther.setVisible(true);
                txtOther.setText(data.get(8));
                if(contactArray.get(LstCt.getSelectionModel().getSelectedIndex()) instanceof Family){
                    lblOther.setVisible(true);
                    lblOther.setText("Relation");
                    txtOther.setVisible(true);
                    cbxType.setValue("Family");
                } else if(contactArray.get(LstCt.getSelectionModel().getSelectedIndex()) instanceof  Professional){
                    lblOther.setVisible(true);
                    lblOther.setText("Work Place");
                    txtOther.setVisible(true);
                    cbxType.setValue("Professional");
                }
            } else { //Reset when it comes back to friends
                txtOther.setVisible(false);
                lblOther.setVisible(false);
                cbxType.setValue("Friend");
            }
            cbxType.setDisable(true);
            imported = true;
            TestFields();
        }
        /**
         * Delete a contact
         */
        @FXML
        protected void Delete() {
            contactArray.remove(selectedID);
            ShowAll();
        }
    
        /**
         * Edit selected contact with new info
         */
        @FXML
        protected void Edit() {
            List<String> firstName = SplitLine(txtFirst.getText(),  " ");
            String lastName = txtLast.getText();
            String address = txtAdd.getText();
            List<String> phone = SplitLine(txtPhone.getText(),  " ");
            List<String> emails = SplitLine(txtEmail.getText(),  " ");
            List<String> social = SplitLine(txtSocial.getText(),  " ");
            String job = txtJob.getText();
            String other = txtOther.getText();
            int selected_id = LstCt.getSelectionModel().getSelectedIndex();
    
            contactArray.get(selected_id).setFirstName(firstName);
            contactArray.get(selected_id).setLastName(lastName);
            contactArray.get(selected_id).setAddr(address);
            contactArray.get(selected_id).setPhone(phone);
            contactArray.get(selected_id).setEmail(emails);
            contactArray.get(selected_id).setSocial(social);
            contactArray.get(selected_id).setJob(job);
            if(contactArray.get(selected_id) instanceof Family){
                Family fam = (Family)contactArray.get(selected_id);
                fam.setRelation(other);
                contactArray.set(selected_id, fam);
            } else if(contactArray.get(selected_id) instanceof Professional){
                Professional pro = (Professional)contactArray.get(selected_id);
                pro.setWork(other);
                contactArray.set(selected_id, pro);
            }
            ShowAll();
        }
        /**
         * Test text in TextBox for First Name, Last Name and Email -> Enable/Disable button accordingly
         */
        @FXML
        public void TestFields(){
            Pattern pat = Pattern.compile("^(.+)@(.+)\\.(.+)$", Pattern.CASE_INSENSITIVE);
            Matcher match = pat.matcher(txtEmail.getText());
    
            if(!txtFirst.getText().equals("") && !txtLast.getText().equals("") //Only first and last names are mandatory
                    && (match.find() || txtEmail.getText().equals(""))){ //but if you put an email, it needs to be valid
                if(imported){ //Selected from list, can both save and edit
                    btnEdit.setDisable(false);
                    btnAdd.setDisable(true);
                } else{ //New contact, can't edit
                    btnEdit.setDisable(true);
                    btnAdd.setDisable(false);
                }
            } else { //No contact, can't save nor edit
                btnEdit.setDisable(true);
                btnAdd.setDisable(true);
            }
        }
        /**
         * Show all Contact in the list & reset text fields
         */
        @FXML
        protected void ShowAll() {
            int cpt_id = 0;
            imported = false;
            btnEdit.setDisable(true);
            btnAdd.setDisable(true);
    
            for(Contact cont: contactArray){ //Give the correct id to the contact (based on their place in the list
                cont.setId(cpt_id);
                cpt_id++;
            }
            LstCt.getItems().clear();
            for(Contact c: contactArray){
                LstCt.getItems().add(c.toString());
            }
    
            txtFirst.setText("");
            txtLast.setText("");
            txtAdd.setText("");
            txtPhone.setText("");
            txtEmail.setText("");
            txtSocial.setText("");
            txtJob.setText("");
            txtOther.setText("");
            cbxType.setDisable(false);
        }
        /**
         * Set the data for a Friend
         */
        public void AddPal(){
            String firstName = txtFirst.getText();
            String lastName = txtLast.getText();
            String address = txtAdd.getText();
            String phone = txtPhone.getText();
            String emails = txtEmail.getText();
            String social = txtSocial.getText();
            String job = txtJob.getText();
    
            List<String> first_name_list = Arrays.asList(firstName.split(","));
            List<String> phoneList = Arrays.asList(phone.split(","));
            List<String> emailList = Arrays.asList(emails.split(","));
            List<String> socialList = Arrays.asList(social.split(","));
    
            Friend pal = new Friend(first_name_list, lastName, address, phoneList, emailList, socialList, job);
            Add(pal);
        }
        /**
         * Set the data for a Family Member
         */
        public void AddFam(){
            String firstName = txtFirst.getText();
            String lastName = txtLast.getText();
            String address = txtAdd.getText();
            String phone = txtPhone.getText();
            String emails = txtEmail.getText();
            String social = txtSocial.getText();
            String job = txtJob.getText();
            String relation = txtOther.getText();
    
            List<String> first_name_list = Arrays.asList(firstName.split(" "));
            List<String> phoneList = Arrays.asList(phone.split(" "));
            List<String> emailList = Arrays.asList(emails.split(" "));
            List<String> socialList = Arrays.asList(social.split(" "));
    
            Family fam = new Family(first_name_list, lastName, address, phoneList, emailList, socialList, job, relation);
            Add(fam);
        }
        /**
         * Set the data for a Professional
         */
        public void AddPro(){
            String firstName = txtFirst.getText();
            String lastName = txtLast.getText();
            String address = txtAdd.getText();
            String phone = txtPhone.getText();
            String emails = txtEmail.getText();
            String social = txtSocial.getText();
            String job = txtJob.getText();
            String wp = txtOther.getText();
    
            List<String> first_name_list = Arrays.asList(firstName.split(" "));
            List<String> phoneList = Arrays.asList(phone.split("/"));
            List<String> emailList = Arrays.asList(emails.split("/"));
            List<String> socialList = Arrays.asList(social.split("/"));
    
            Professional pro = new Professional(first_name_list, lastName, address, phoneList,
                    emailList, socialList, job, wp);
            Add(pro);
        }
        /**
         * Add a contact to the list
         * @param c Contact to add
         */
        public void Add(Contact c){
            contactArray.add(c);
            Collections.sort(contactArray);
            ShowAll();
        }
        /**
         * Import a Friend
         * @param str_array Friends informations
         */
        public void ImportFriend(List<String> str_array){
            Friend f = new Friend(
                    SplitLine(str_array.get(1), " "),
                    str_array.get(2),
                    str_array.get(3),
                    SplitLine(str_array.get(4), " "),
                    SplitLine(str_array.get(5), " "),
                    SplitLine(str_array.get(6), " "),
                    str_array.get(7)
            );
            f.setId(Integer.parseInt(str_array.get(0)));
            Add(f);
        }
        /**
         * Import a Family Member
         * @param str_array Family member  informations
         */
        public void ImportFamily(List<String> str_array){
            Family f = new Family(
                    SplitLine(str_array.get(1), " "),
                    str_array.get(2),
                    str_array.get(3),
                    SplitLine(str_array.get(4), " "),
                    SplitLine(str_array.get(5), " "),
                    SplitLine(str_array.get(6), " "),
                    str_array.get(7),
                    str_array.get(8)
            );
            f.setId(Integer.parseInt(str_array.get(0)));
            Add(f);
        }
    
        /**
         * Import a Professional
         * @param str_array Professional informations
         */
        public void ImportProfessional(List<String> str_array){
            Professional f = new Professional(
                    SplitLine(str_array.get(1), " "),
                    str_array.get(2),
                    str_array.get(3),
                    SplitLine(str_array.get(4), " "),
                    SplitLine(str_array.get(5), " "),
                    SplitLine(str_array.get(6), " "),
                    str_array.get(7),
                    str_array.get(8)
            );
            f.setId(Integer.parseInt(str_array.get(0)));
            Add(f);
        }
        /**
         * Add a contact (any type) to the list
         * @param str_array contact info
         * @param checker checker to verify contact type
         */
        public void AddContactToList(List<String> str_array, int checker){
            switch (checker){
                case 1 -> ImportFriend(str_array);
                case 2 -> ImportFamily(str_array);
                case 3 -> ImportProfessional(str_array);
            }
        }
        /**
         * Split a String into String array
         * @param str list to split, splitter: string used as separator
         * @return a List of all the words in the string
         */
        public List<String> SplitLine(String str, String splitter){
            return Arrays.asList(str.split(splitter));
        }
    }