Phone book application example - Java

This post will show one example of a PhoneBook Application developed using Java language. All of the contacts will be store into a .txt file without using the database. This is an example only. You can change the layout or add some features to this example.

Note: This tutorial using Netbean v 7.4

Step by step:

  1. Create a New Project and choose Java Application
  2. Rename Project Name to PhoneContact
  3. Delete file PhoneContact.java
  4. Add New JFrame Form under package phonecontact and change class Name to MainUI
  5. Drag and drop java Swing controller into frame. Refer MainUI below. ( Note: you can change the position of button as you like)
  6. Add new JFrame Form under package phonecontact and change class name to AddEditForm.
  7. Drag and drop java sing controller into frame, Refer AddEditForm image below.
  8. Create 2 Java Class. Contact.java and ContactsUtility.java.
  9. Copy paste the code behind of each java class and frame.
  10.  

MainUI code behind

 import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author developersnote
 */
public class MainUserInterface extends javax.swing.JFrame {

    /**
     * Creates new form MainUserInterface
     */
    public MainUserInterface() {
        initComponents();
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        this.addWindowListener(getWindowAdapter());
        jTable1.getTableHeader().setFont(new java.awt.Font("Verdana", 0, 11));
        //load contacts into ArrayList
        ContactsUtility.readPhoneContacts();
        //bind into JTable
        BindIntoJTable();
    }

    //make public and for enable to access from another class
    public static void BindIntoJTable() {
        //clear jTable First
        jTable1.removeAll();
        List<Contact> AllContacts = ContactsUtility.getAllContacts();
        if (AllContacts != null) {          
            int index = 1;
            String colNames[] = {"No","Name", "Contacts No", "Email Address"};
            DefaultTableModel dtm = new DefaultTableModel(null, colNames);

            for (int i = 0; i < AllContacts.size(); i++) {
                dtm.addRow(new String[4]);
            }
            jTable1.setModel(dtm);

            if (AllContacts.size() > 0) {
                int row = 0;
                for (Contact c : AllContacts) {
                    jTable1.setValueAt(Integer.toString(index), row, 0);                                      
                    jTable1.setValueAt(c.getName(), row, 1);
                    jTable1.setValueAt(c.getPhoneNo(), row, 2);                  
                    jTable1.setValueAt(c.getEmailAddress(), row, 3);
                    index++;                  
                    row++;
                }
                jTable1.getColumn("No").setMaxWidth(30);
                jTable1.getColumn("Name").setMaxWidth(130);
                jTable1.getColumn("Contacts No").setMaxWidth(110);
                jTable1.getColumn("Email Address").setMaxWidth(110);
                jTextStatus.setText("Finish Load Contact," + Integer.toString(AllContacts.size())
                        + " records found");
            }else{
                jTextStatus.setText("Finish Load Contact, No record Found");
            }
        }
    }

    private WindowAdapter getWindowAdapter() {
        return new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent we) {//override to show message
                super.windowClosing(we);
                if (JOptionPane.showConfirmDialog(null, "Are you sure to close this application?",
                        "Confirmation Box", JOptionPane.OK_CANCEL_OPTION) == 0) { //clicked ok
                    CloseApp();
                }
            }
        };
    }

    public void CloseApp() {
        this.dispose();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                        
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jTextStatus = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jTextSearch = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Phone Contacts - Group");
        setResizable(false);

        jScrollPane1.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N

        jTable1.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Name", "Contacts No", "Email Address"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jButton1.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        jButton1.setText("Add Contact");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        jButton2.setText("Edit");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        jButton3.setText("Delete");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jTextStatus.setBackground(new java.awt.Color(153, 153, 153));
        jTextStatus.setFont(new java.awt.Font("Verdana", 3, 11)); // NOI18N
        jTextStatus.setToolTipText("This is a Application Status");
        jTextStatus.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jTextStatus.setDisabledTextColor(new java.awt.Color(255, 255, 255));
        jTextStatus.setEnabled(false);

        jLabel1.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 102, 102));
        jLabel1.setText("Search Contact");

        jTextSearch.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N

        jButton4.setText("Search");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        jButton5.setText("Reload Contacts");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jMenu1.setText("About Application");
        jMenu1.addMenuListener(new javax.swing.event.MenuListener() {
            public void menuCanceled(javax.swing.event.MenuEvent evt) {
            }
            public void menuDeselected(javax.swing.event.MenuEvent evt) {
            }
            public void menuSelected(javax.swing.event.MenuEvent evt) {
                jMenu1MenuSelected(evt);
            }
        });
        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTextStatus)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton4))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton5)))
                        .addGap(0, 3, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton2)
                        .addComponent(jButton3)
                        .addComponent(jButton5)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jTextStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                      

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        //Add Contact
        AddEditForm Form = new AddEditForm();
        Form.setFormMode(true);//true for add mode
        Form.UpdateStatus();
        Form.setVisible(true);
    }                                      

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        int row = jTable1.getSelectedRow();
        //if row is -1 mean user have not select any row yet
        if(row != -1){
          
            String nama = (String)jTable1.getValueAt(row,1);//cast object to string
            String PhoneNo = (String)jTable1.getValueAt(row,2);//cast object to string
            String email = (String)jTable1.getValueAt(row,3);//cast object to string
          
            Contact C = new Contact();
            C.setEmailAddress(email);
            C.setName(nama);
            C.setPhoneNo(PhoneNo);
       
            AddEditForm dlg = new AddEditForm();
            dlg.setFormMode(false);//true for add mode
            dlg.MapTextBox(C);
            dlg.UpdateStatus();
            dlg.setVisible(true);          
        }
      
              
    }                                      

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                       
         int row = jTable1.getSelectedRow();
        //if row is -1 mean user have not select any row yet
        if(row != -1){
            String nama = (String)jTable1.getValueAt(row,1);//cast object to string
            String PhoneNo = (String)jTable1.getValueAt(row,2);//cast object to string
            String email = (String)jTable1.getValueAt(row,3);//cast object to string
          
            Contact C = new Contact();
            C.setEmailAddress(email);
            C.setName(nama);
            C.setPhoneNo(PhoneNo);
          
            if (JOptionPane.showConfirmDialog(null, "Are you sure to delete contact : " + nama + "?",
                    "Confirmation Box", JOptionPane.OK_CANCEL_OPTION) == 0) { //clicked ok
                ContactsUtility.deleteContacts(C);
            }
        }
    }                                      

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        //reload Contacts      
        ContactsUtility.readPhoneContacts();      
        BindIntoJTable();
    }                                      

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        String searchValue = jTextSearch.getText();
        List<Contact> contacts = ContactsUtility.searchContact(searchValue);
        ContactsUtility.setAllContacts(contacts);
        BindIntoJTable();
    }                                      

    private void jMenu1MenuSelected(javax.swing.event.MenuEvent evt) {                                  
        // do nothing   
    }                                 

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainUserInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainUserInterface().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                   
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private static javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextSearch;
    private static javax.swing.JTextField jTextStatus;
    // End of variables declaration                 
}

AddEditForm code behind

 import javax.swing.JOptionPane;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author developersnote
 */
public class AddEditForm extends javax.swing.JFrame {

    private boolean formMode;// true for add, false for edit
    private Contact editContactDetails;
  
  
    /**
     * Creates new form AddEditForm
     */
    public AddEditForm() {
        initComponents();      
    }
  
    public void UpdateStatus(){
        if(formMode){
            jTextStatus.setText("Add Contact Mode");
            jButton1.setText(formMode ? "Save" : "Update");
        }else{
            jTextStatus.setText("Edit Contact Mode");
            jButton1.setText(formMode ? "Save" : "Update");
        }
    }
  
    public void MapTextBox(Contact c){
        if(c != null){
            JTextName.setText(c.getName());
            JTextPhone.setText(c.getPhoneNo());
            jTextEmail.setText(c.getEmailAddress());
            editContactDetails = c;
        }
    }
   
     protected void CloseDialog()
     {
         this.dispose();
     }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                        
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        JTextName = new javax.swing.JTextField();
        JTextPhone = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextEmail = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextStatus = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Verdana", 1, 14)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 102, 102));
        jLabel1.setText("Contact Information");

        jLabel2.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        jLabel2.setText("Name");

        JTextName.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N

        JTextPhone.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        JTextPhone.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                JTextPhoneKeyPressed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        jLabel3.setText("Contact No");

        jTextEmail.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N

        jLabel4.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        jLabel4.setText("Email Address");

        jButton1.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        jButton1.setText("Save");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        jButton2.setText("Cancel");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextStatus.setBackground(new java.awt.Color(153, 153, 153));
        jTextStatus.setFont(new java.awt.Font("Verdana", 3, 11)); // NOI18N
        jTextStatus.setForeground(new java.awt.Color(255, 255, 255));
        jTextStatus.setToolTipText("This is a Contact Information Status");
        jTextStatus.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jTextStatus.setDisabledTextColor(new java.awt.Color(255, 255, 255));
        jTextStatus.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jTextEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(JTextPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(JTextName, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(23, Short.MAX_VALUE))
            .addComponent(jTextStatus)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(JTextName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(JTextPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addComponent(jTextStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                      

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        CloseDialog();
    }                                      

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
        String Name = JTextName.getText();
        String Phone = JTextPhone.getText();
        String Email = jTextEmail.getText();
        String buildContact = "";
      
        if(!Name.isEmpty()){
            buildContact += Name + ",";
        }else {
            buildContact += "NULL" + ",";
        }
      
        if(!Phone.isEmpty()){
            buildContact += Phone + ",";
        }else {
            buildContact += "NULL" + ",";
        }
      
        if(!Email.isEmpty()){
            buildContact += Email + ",";
        }else {
            buildContact += "NULL" + ",";
        }
      
        buildContact = buildContact.substring(0,buildContact.length() -1);
      
        if(formMode){
            if(ContactsUtility.appendTextContact(buildContact + "\r\n")){
                JOptionPane.showMessageDialog(null,"Successfully add contact : " + Name);              
                ContactsUtility.readPhoneContacts(); // re read contact file to reload arrayList
                MainUserInterface.BindIntoJTable();
                CloseDialog();
            }else{
                JOptionPane.showMessageDialog(null,"Failed to add contact : " + Name);
            }
        }else{
            if(ContactsUtility.updateContact(editContactDetails.getName(),
                    editContactDetails.getPhoneNo(),
                    editContactDetails.getEmailAddress(), buildContact)){
                JOptionPane.showMessageDialog(null,"Successfully update contact : " + Name);
                ContactsUtility.readPhoneContacts(); // re read contact file to reload arrayList
                MainUserInterface.BindIntoJTable();
                CloseDialog();
            }else{
                JOptionPane.showMessageDialog(null,"Failed to update contact : " + Name);
            }              
        }
      
    }                                      

    private void JTextPhoneKeyPressed(java.awt.event.KeyEvent evt) {                                    
        if(JTextPhone.getText().length() == 12){
            JTextPhone.setText(JTextPhone.getText().substring(0,JTextPhone.getText().length() -1));
        }
    }                                   

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddEditForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AddEditForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                   
    private javax.swing.JTextField JTextName;
    private javax.swing.JTextField JTextPhone;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextEmail;
    private javax.swing.JTextField jTextStatus;
    // End of variables declaration                 

    /**
     * @return the formMode
     */
    public boolean isFormMode() {
        return formMode;
    }

    /**
     * @param formMode the formMode to set
     */
    public void setFormMode(boolean formMode) {
        this.formMode = formMode;
    }

    /**
     * @return the editContactDetails
     */
    public Contact getEditContactDetails() {
        return editContactDetails;
    }

    /**
     * @param editContactDetails the editContactDetails to set
     */
    public void setEditContactDetails(Contact editContactDetails) {
        this.editContactDetails = editContactDetails;
    }
}


Contact.java class

 /**
 *
 * @author developersnote
 */
public class Contact {
  
    private String Name;
    private String PhoneNo;
    private String EmailAddress;
  
    public Contact()
    {
        Name = "";
        PhoneNo = "";
        EmailAddress = "";
    }

    /**
     * @return the Name
     */
    public String getName() {
        return Name;
    }

    /**
     * @param Name the Name to set
     */
    public void setName(String Name) {
        this.Name = Name;
    }

    /**
     * @return the PhoneNo
     */
    public String getPhoneNo() {
        return PhoneNo;
    }

    /**
     * @param PhoneNo the PhoneNo to set
     */
    public void setPhoneNo(String PhoneNo) {
        this.PhoneNo = PhoneNo;
    }

    /**
     * @return the EmailAddress
     */
    public String getEmailAddress() {
        return EmailAddress;
    }

    /**
     * @param EmailAddress the EmailAddress to set
     */
    public void setEmailAddress(String EmailAddress) {
        this.EmailAddress = EmailAddress;
    }
  
}


ContactsUtility.java class

 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.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author developersnote
 */
public class ContactsUtility {

    private static List<Contact> AllContacts;
    private static String MessageStatus;
    public static final String ContactFileName = "Contacts.txt";

    /**
     * @return the MessageStatus
     */
    public static String getMessageStatus() {
        return MessageStatus;
    }

    /**
     * @param aMessageStatus the MessageStatus to set
     */
    public static void setMessageStatus(String aMessageStatus) {
        MessageStatus = aMessageStatus;
    }

    public ContactsUtility() {
        AllContacts = new ArrayList<Contact>();
    }

    public static boolean updateContact(String name, String PhoneNo, String emailAdd, String NewStringLine) {
        BufferedReader br = null;
        String ReWrite = "";
        boolean success = false;
        try {
            if (new File(ContactFileName).exists()) {
                br = new BufferedReader(new FileReader(ContactFileName));
                String line = "";
                while ((line = br.readLine()) != null) {
                    if (!"".equals(line)) {
                        String[] _temp = line.split(",");
                        if (_temp[0].equalsIgnoreCase(name) && _temp[1].equalsIgnoreCase(PhoneNo)
                                && _temp[2].equalsIgnoreCase(emailAdd)) {
                            ReWrite += NewStringLine + "\r\n";
                        } else {
                            ReWrite += line + "\r\n";
                        }
                    }
                }
                br.close();

                if (writeFile(ReWrite)) {
                    success = true;
                } else {
                    success = false;
                }
                //update ArrayList with new Contact List
                readPhoneContacts();

            } else {
                new File(ContactFileName).createNewFile();
                readPhoneContacts();
                success = false;
            }
        } catch (FileNotFoundException ex) {
            MessageStatus = ex.getMessage();
            success = false;
        } catch (IOException ex) {
            MessageStatus = ex.getMessage();
            success = false;
        }
        return success;
    }

    public static List<Contact> searchContact(String searchValue) {
        List<Contact> cnt = new ArrayList<>();
        BufferedReader br = null;

        try {
            if (new File(ContactFileName).exists()) {
                br = new BufferedReader(new FileReader(ContactFileName));
                String line = "";
                while ((line = br.readLine()) != null) {
                    if (!"".equals(line)) {
                        String[] _temp = line.split(",");
                        if (_temp[0].equalsIgnoreCase(searchValue) || _temp[1].equalsIgnoreCase(searchValue)
                                || _temp[2].equalsIgnoreCase(searchValue)) {
                            Contact c = new Contact();
                            c.setName(_temp[0]);
                            c.setPhoneNo(_temp[1]);
                            c.setEmailAddress(_temp[2]);
                            cnt.add(c);
                        }
                    }
                }
            } else {
                new File(ContactFileName).createNewFile();
                cnt = searchContact(searchValue);
            }
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } finally {
            try {
                br.close();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }
        }

        return cnt;
    }

    protected static boolean writeFile(String TextToWrite) {
        FileWriter writer = null;
        boolean successfulWrite = false;
        try {
            writer = new FileWriter(ContactFileName);
            writer.write(TextToWrite);
            writer.close();
            successfulWrite = true;
        } catch (IOException ex) {
            successfulWrite = false;
            MessageStatus = ex.getMessage();
        } finally {
            try {
                writer.close();
            } catch (IOException ex) {
                MessageStatus = ex.getMessage();
            }
        }
        return successfulWrite;
    }

    public static void deleteContacts(Contact C) {
        BufferedReader br = null;
        String ReWrite = "";
        try {
            if (new File(ContactFileName).exists()) {
                br = new BufferedReader(new FileReader(ContactFileName));
                String line = "";
                while ((line = br.readLine()) != null) {
                    String[] _temp = line.split(",");
                    if (_temp[0].equalsIgnoreCase(C.getName()) && _temp[1].equalsIgnoreCase(C.getPhoneNo())
                            && _temp[2].equalsIgnoreCase(C.getEmailAddress())) {
                        //ignore line to delete this contact
                    } else {
                        ReWrite += line + "\r\n";
                    }
                }
                br.close();

                if (writeFile(ReWrite)) {
                    JOptionPane.showMessageDialog(null, "Successfully delete contact " + C.getName());
                } else {
                    JOptionPane.showMessageDialog(null, "Failed to delete contact " + C.getName());
                }

                ContactsUtility.readPhoneContacts();
                MainUserInterface.BindIntoJTable();

            } else {
                new File(ContactFileName).createNewFile();
                readPhoneContacts();
            }
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    public static void readPhoneContacts() {
        //read Contacts file and store into arraylist of Object(contact)
        BufferedReader br = null;
        try {
            if (new File(ContactFileName).exists()) {

                if (AllContacts == null) {
                    AllContacts = new ArrayList<>();
                } else {
                    AllContacts.clear();
                }
                br = new BufferedReader(new FileReader(ContactFileName));
                StringBuilder sb = new StringBuilder();
                String line = "";
                Contact ContactClass = null;
                while ((line = br.readLine()) != null) {
                    if (!line.equalsIgnoreCase("")) {
                        ContactClass = new Contact();
                        String[] _temp = line.split(",");
                        String _tempValue = _temp[0];
                        if (_tempValue.equalsIgnoreCase("NULL")) {
                            _tempValue = "";
                        }
                        ContactClass.setName(_tempValue);

                        _tempValue = _temp[1];
                        if (_tempValue.equalsIgnoreCase("NULL")) {
                            _tempValue = "";
                        }
                        ContactClass.setPhoneNo(_tempValue);

                        _tempValue = _temp[2];
                        if (_tempValue.equalsIgnoreCase("NULL")) {
                            _tempValue = "";
                        }
                        ContactClass.setEmailAddress(_tempValue);
                        AllContacts.add(ContactClass);
                    }
                }
            } else {
                new File(ContactFileName).createNewFile();
                readPhoneContacts();
            }

        } catch (NullPointerException | IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                    Logger.getLogger(ContactsUtility.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }

    public static boolean appendTextContact(String appendValue) {
        boolean success = false;
        try {
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(ContactFileName, true)));
            out.println(appendValue);
            out.close();
            success = true;
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
        return success;
    }

    /**
     * @return the AllContacts
     */
    public static List<Contact> getAllContacts() {
        return AllContacts;
    }

    /**
     * @param aAllContacts the AllContacts to set
     */
    public static void setAllContacts(List<Contact> aAllContacts) {
        AllContacts = aAllContacts;
    }

}

Popular posts from this blog

How to create zip file to download in JSP- Servlet

How to create DataGrid or GridView in JSP - Servlet

Pinging in ASP.NET Example