Wednesday, 5 February 2014

Java - PhoneBook Application Example

Leave a Comment
This post will show one example of PhoneBook Application developerd using Java langguage.All of contact will be store into txt file without using database. This is only example. You can change the layout or add some feature into this example.

Note : This tutorial using Netbean v 7.4

Step by step:

  1. Create 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;
    }

}


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Tuesday, 4 February 2014

MVC - URL Routing

Leave a Comment


 The segments in an examle URL

The first segment contains the word Admin, and the second segment contains the word Index. To the
human eye, it is obvious that the first segment relates to the controller and the second segment relates to the action. But, of course, we need to express this relationship in a way that the routing system can
understand. Here is a URL pattern that does this:

{controller}/{action}
or
{controller}/{action}/id
or
{controller}/{action}/id?querystring2=&querystring3=

 Note : id, querystring2, and querystring 3 is a parameter in the controller.

When processing an incoming request, the job of the routing system is to match the URL that has
been requested to a pattern and extract values from the URL for the segment variables defined in the
pattern. The segment variables are expressed using braces (the { and } characters). The example pattern has two segment variables with the names controller and action, and so the value of the controller segment variable will be Admin and the value of the action segment variable will be Index.

Customize the routing rules that MVC uses to locate an action.

App_Start >> RouteCinfig.cs

 
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index",
              id = UrlParameter.Optional }
);

Make Routing support url like :

/Admin/Index/id/querystring2/querystring3

 
routes.MapRoute(
            name : "Default",  
            url  :  "{controller}/{action}/{id}/{querystring2}/querystring3", 
            defaults : new { controller = "Home", action = "Index",
                id= UrlParameter.Optional,
                querystring2=UrlParameter.Optional, 
                querystring3 =UrlParameter.Optional } 
);

By NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Understanding the ASP.NET MVC Framework Pattern

Leave a Comment
In high-level terms, the MVC pattern means that an MVC application will be split into at least three pieces:

  • Models, which contain or represent the data that users work with. These can be simple view models, which just represent data being transferred between views and controllers; or they can be domain models, which contain the data in a business domain as well as the operations, transformations, and rules for manipulating that data.
  • Views, which are used to render some part of the model as a user interface.
  • Controllers, which process incoming requests, perform operations on the model,and select views to render to the user.

Models are the definition of the universe your application works in. In a banking application, for
example, the model represents everything in the bank that the application supports, such as accounts, the general ledger, and credit limits for customers as well as the operations that can be used to manipulate the data in the model, such as depositing funds and making withdrawals from the accounts.
The model is also responsible for preserving the overall state and consistency of the data. For example, making sure that all transactions are added to the ledger, and that a client doesn’t withdraw more money than he is entitled to or more money than the bank has.

Models are also defined by what they are not responsible for: models don’t deal with rendering UIs or processing requests. Those are the responsibilities of views and controllers. Views contain the logic required to display elements of the model to the user and nothing more. They have no direct awareness of the model and do not directly communicate with the model in any way.  
Controllers are the bridge between views and the model. The requests come in from the client and are serviced by the controller, which selects an appropriate view to show the user and, if required, an appropriate operation to perform on the model.

Each piece of the MVC architecture is well-defined and self-contained. This is referred to as the
separation of concerns. The logic that manipulates the data in the model is contained only in the model; the logic that displays data is only in the view, and the code that handles user requests and input is contained only in the controller. With a clear division between each of the pieces, your application will be easier to maintain and extend over its lifetime, no matter how large it becomes.


The interactions in an MVC application


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Monday, 3 February 2014

MVC 4 - Example sending email - WebMail

Leave a Comment
This is a example of sending email snippet code in Razor Editor.

Sample Sending Email - Razor

 
@{
Layout = null;
}
<!DOCTYPE html>
 <html>
  <head>
   <meta name="viewport" content="width=device-width" />
   <title>Thanks</title>
  </head>
<body>
     @{
       try {
         WebMail.SmtpServer = "smtp.example.com";
         WebMail.SmtpPort = 587;
         WebMail.EnableSsl = true;
         WebMail.UserName = "mySmtpUsername";
         WebMail.Password = "mySmtpPassword";
         WebMail.From = "rsvps@example.com";
         WebMail.Send("party-host@example.com", "RSVP Notification",
                 "Message Send will be here");
       } 
      catch (Exception) 
      {
          @:<b>Sorry - we couldn't send the email to confirm your RSVP.</b>
       }
     }
<div>
</div>
</body>
</html>


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Sunday, 2 February 2014

MVC 4 - Adding Validation in a form

Leave a Comment
This is a example of adding a validation in MVC form. Please refer to this post for reference of this example.

Adding error message and validation rule

GuestResponse.cs
 
using System;
using System.Collections.Generic;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MyFirstMVCApp.Models
{
    public class GuestResponse
    {
        [Required(ErrorMessage = "Please enter your name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please enter your email address")]
        [RegularExpression(".+\\@.+\\..+",
        ErrorMessage = "Please enter a valid email address")]
        public string Email { get; set; }

        [Required(ErrorMessage = "Please enter your phone number")]
        public string Phone { get; set; }

        [Required(ErrorMessage = "Please specify whether you'll attend")]
        public bool? WillAttend { get; set; }
    }
}


HomeController.cs
 
        [HttpPost]
        public ViewResult RsvpForm(GuestResponse guestResponse)
        {
            if (ModelState.IsValid)
            {
                // TODO: Email response to the party organizer
                return View("Thanks", guestResponse);
            }
            else
            {
                // there is a validation error
                return View();
            }
        }


RsvpForm.cshtml
 
<head>
    <meta name="viewport" content="width=device-width" />
    <title>RsvpForm</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            @Html.ValidationSummary()
            <p>
                Your name: @Html.TextBoxFor(x => x.Name)
            </p>
            <p>
                Your email: @Html.TextBoxFor(x => x.Email)</p>
            <p>
                Your phone: @Html.TextBoxFor(x => x.Phone)</p>
            <p>
                Will you attend?
                @Html.DropDownListFor(x => x.WillAttend, new[] { 
                   new SelectListItem() {
                       Text = "Yes, I'll be there", 
                       Value = bool.TrueString
                   },
                   new SelectListItem() {
                       Text = "No, I can't come",
                       Value = bool.FalseString
                   }
           },
           "Choose an option") 
            </p>
            <input type="submit" value="Submit RSVP" />
        }
    </div>
</body>
</html> 

Highlight Invalid Field

add this css style

.field-validation-error {color: #f00;}
.field-validation-valid { display: none;}
.input-validation-error { border: 1px solid #f00; background-color: #fee; }
.validation-summary-errors { font-weight: bold; color: #f00;}
.validation-summary-valid { display: none;}




By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

MVC 4 - Creating simple Data-Entry Application

Leave a Comment
This example will show how to create simple data entry form in MVC4 asp.net.

Step By Step Creating Data Entry Application

  1. File >> New Project
  2. Choose ASP.NET MVC4 Web Application. (If you dont have MVC 4, Install it here)
  3. On Project Template, choose Empty if you want to start from zero or choose Internet Application to start developement with default template.
  4. Choose View engine Razor.
  5. Click OK button
  6.  Create HomeController.cs under Controller Folder.
  7. Create GuestResponse.cs Model
  8. Create RsvpForm,Thanks, and Index View under View >> Home folder.
  9. See the file code example below.

HomeController.cs

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyFirstMVCApp.Models;

namespace MyFirstMVCApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ViewResult Index()
        {
            return View();
        }

        public ViewResult RsvpForm()
        {
            return View();
        }

        [HttpPost]
        public ViewResult RsvpForm(GuestResponse guestResponse)
        {
            // TODO: Email response to the party organizer
            return View("Thanks", guestResponse);
        }

    }
}


GuestResponse.cs

 
using System;
using System.Collections.Generic;
using System.Web;

namespace MyFirstMVCApp.Models
{
    public class GuestResponse
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public bool? WillAttend { get; set; }
    }
}


Index.cshtml

 


@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        div>
        @ViewBag.Greeting World (from the view)
        <p>
            We're going to have an exciting party.<br />
            (To do: sell it better. Add pictures or something.)
        </p>
        @Html.ActionLink("RSVP Now", "RsvpForm")
    </div>
</body>
</html>


RsvpForm.cshtml

 
@model MyFirstMVCApp.Models.GuestResponse
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>RsvpForm</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            <p>
                Your name: @Html.TextBoxFor(x => x.Name)
            </p>
            <p>
                Your email: @Html.TextBoxFor(x => x.Email)</p>
            <p>
                Your phone: @Html.TextBoxFor(x => x.Phone)</p>
            <p>
                Will you attend?
                @Html.DropDownListFor(x => x.WillAttend, new[] { 
                   new SelectListItem() {
                       Text = "Yes, I'll be there", 
                       Value = bool.TrueString
                   },
                   new SelectListItem() {
                       Text = "No, I can't come",
                       Value = bool.FalseString
                   }
           }, 
           "Choose an option") 
            </p>
            <input type="submit" value="Submit RSVP" />
        }
    </div>
</body>
</html>


Thanks.cshtml

 
@model MyFirstMVCApp.Models.GuestResponse
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Thanks</title>
</head>
<body>
    <div>
        <h1>
            Thank you, @Model.Name!</h1>
        @if (Model.WillAttend == true)
        {
            @:It's great that you're coming. The drinks are already in the fridge!
        }
        else
        {
            @:Sorry to hear that you can't make it, but thanks for letting us know.
        }
    </div>
</body>
</html>


Have a try this tutorial.

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.