วันพฤหัสบดีที่ 6 กันยายน พ.ศ. 2555

jFrameMyFriend.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jFrameMyFriend.java
 *
 * Created on 20 ต.ค. 2554, 0:44:03
 */

package telephone;

import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Panyapol
 */
public class jFrameMyFriend extends javax.swing.JFrame {

    private Connection conn = MyConnect.getConnection();
    private DefaultTableModel modelFriend;

    /** Creates new form jFrameMyFriend */
    public jFrameMyFriend() {
        initComponents();

        modelFriend = (DefaultTableModel) tableFriend.getModel(); //ผูกข้อมูลใน DB เข้ากับ Table
    }

    //นำข้อมูลใน DB Table มาแสดงบนตารางของโปรแกรม
    public void bindData(){
        try{
           
            //Clear record
            int totalRow = tableFriend.getRowCount() - 1;
            while(totalRow > - 1){
                modelFriend.removeRow(totalRow);
                totalRow--;
            }

            //Add record
            String search = txtSearch.getText();
            String sql = ""
                    + "SELECT * FROM tb_friend"
                    + " WHERE "
                    + "     name LIKE ('%" + search + "%')"
                    + "     OR tel LIKE ('%" + search + "%')"
                    + "     OR email LIKE ('%" + search + "%')"
                    + "     OR job LIKE ('%" + search + "%')";
           
            ResultSet rs = conn.createStatement().executeQuery(sql);
            int row = 0;

            while (rs.next()){
                modelFriend.addRow(new Object[0]);
                modelFriend.setValueAt(rs.getInt("id"), row, 0);
                modelFriend.setValueAt(rs.getString("name"), row, 1);
                modelFriend.setValueAt(rs.getString("tel"), row, 2);
                modelFriend.setValueAt(rs.getString("email"), row, 3);
                modelFriend.setValueAt(rs.getString("job"), row, 4);
                row++;
            }
            tableFriend.setModel(modelFriend);

        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /** 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();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        txtJob = new javax.swing.JTextField();
        txtTel = new javax.swing.JTextField();
        txtEmail = new javax.swing.JTextField();
        cmdSave = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableFriend = new javax.swing.JTable();
        cmdUpdate = new javax.swing.JButton();
        cmdDelete = new javax.swing.JButton();
        cmdClear = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtSearch = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Telephone by Panyapol v.1.0.1");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setText("ชื่อ");

        jLabel2.setText("อาชีพ");

        jLabel3.setText("เบอร์โทร");

        jLabel4.setText("อีเมล์");

        txtJob.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtJobActionPerformed(evt);
            }
        });

        cmdSave.setText("บันทึก");
        cmdSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdSaveActionPerformed(evt);
            }
        });

        tableFriend.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id", "ชื่อเพื่อน", "เบอร์โทร", "อีเมล์", "อาชีพ"
            }
        ));
        tableFriend.setRowHeight(25);
        tableFriend.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableFriendMouseClicked(evt);
            }
        });
        tableFriend.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tableFriendKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tableFriend);
        tableFriend.getColumnModel().getColumn(0).setPreferredWidth(50);
        tableFriend.getColumnModel().getColumn(1).setPreferredWidth(200);
        tableFriend.getColumnModel().getColumn(2).setPreferredWidth(100);
        tableFriend.getColumnModel().getColumn(3).setPreferredWidth(150);
        tableFriend.getColumnModel().getColumn(4).setPreferredWidth(150);

        cmdUpdate.setText("แก้ไข");
        cmdUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdUpdateActionPerformed(evt);
            }
        });

        cmdDelete.setText("ลบ");
        cmdDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdDeleteActionPerformed(evt);
            }
        });

        cmdClear.setText("เครียร์");
        cmdClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdClearActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("ค้นหาเพื่อนของเรา"));

        txtSearch.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtSearchKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(117, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 897, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmdSave)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdUpdate)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdDelete)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdClear))
                            .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(txtJob, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtTel, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtEmail, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)))
                        .addGap(50, 50, 50)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(63, 63, 63))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtJob, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel2))
                                .addGap(11, 11, 11)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cmdSave)
                            .addComponent(cmdUpdate)
                            .addComponent(cmdDelete)
                            .addComponent(cmdClear)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void cmdSaveActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
        try{
            String sql = "INSERT INTO tb_friend (name, tel, email, job) VALUES (?, ?, ?, ?)";
            PreparedStatement pre = conn.prepareStatement(sql);
            pre.setString(1, txtName.getText());
            pre.setString(2, txtTel.getText());
            pre.setString(3, txtEmail.getText());
            pre.setString(4, txtJob.getText());

            if(pre.executeUpdate() != -1){
                JOptionPane.showMessageDialog(this, "บันทึกรายการแล้ว", "ผลการบันทึกรายการ", JOptionPane.INFORMATION_MESSAGE);
                bindData();
            }
       
        }
        catch (Exception e){
            e.printStackTrace();
        }


    }                                      

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                
        // TODO add your handling code here:
        bindData();
    }                                

    private void tableFriendMouseClicked(java.awt.event.MouseEvent evt) {                                        
        // TODO add your handling code here:
        int index = tableFriend.getSelectedRow();
        txtName.setText(tableFriend.getValueAt(index, 1).toString());
        txtTel.setText(tableFriend.getValueAt(index, 2).toString());
        txtEmail.setText(tableFriend.getValueAt(index, 3).toString());
        txtJob.setText(tableFriend.getValueAt(index, 4).toString());
    }                                      

    private void cmdUpdateActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        int index = tableFriend.getSelectedRow();

        if(index != -1){
            int pk = (Integer) tableFriend.getValueAt(index, 0);
            //หรือวิธีนี้   Integer.parseInt(tableFriend.getValueAt(index, 0).toString());
            String sql = ""
                    + " UPDATE tb_friend SET "
                    + "     name = ?,     "
                    + "     tel = ?,      "
                    + "     email = ?,    "
                    + "     job = ?       "
                    + " WHERE id = " + pk;
            try{
                PreparedStatement Pre = conn.prepareStatement(sql);
                Pre.setString(1, txtName.getText());
                Pre.setString(2, txtTel.getText());
                Pre.setString(3, txtEmail.getText());
                Pre.setString(4, txtJob.getText());

                if(Pre.executeUpdate() != -1){
                    JOptionPane.showMessageDialog(this, "บันทึกการแก้ไขแล้ว", "บันทึกรายการ", JOptionPane.INFORMATION_MESSAGE);
                    bindData();
                }
            }catch(Exception e){
                e.printStackTrace();
            }
           
        }
    }                                        

    private void cmdDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        int index = tableFriend.getSelectedRow();

        if(index != -1){
            int pk = (Integer) tableFriend.getValueAt(index, 0); //แปลงจากอ๊อบเจ็กไปเป็นเลขจำนวนเต็ม
            String sql = "DELETE FROM tb_friend WHERE id = " + pk;

            try{
                if(conn.createStatement().executeUpdate(sql) != -1);
                JOptionPane.showMessageDialog(this, "ลบรายการแล้ว", "ลบรายการ", JOptionPane.INFORMATION_MESSAGE);
                //ลบแล้วให้เครียร์ TextBox
                txtName.setText("");
                txtTel.setText("");
                txtEmail.setText("");
                txtJob.setText("");
                //รีเฟรชเทเบิล
                bindData();
            }catch(Exception e){
                e.printStackTrace();
            }          
        }
    }                                        

    //แก้ไขข้อมูลที่ JTable ได้เลย
    private void tableFriendKeyReleased(java.awt.event.KeyEvent evt) {                                      
        // TODO add your handling code here:
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            //Update data
            try{
                int index = tableFriend.getSelectedRow();
                int pk = (Integer) tableFriend.getValueAt(index, 0);

                String sql = ""
                    + " UPDATE tb_friend SET "
                    + "     name = ?,     "
                    + "     tel = ?,      "
                    + "     email = ?,    "
                    + "     job = ?       "
                    + " WHERE id = " + pk;
                PreparedStatement Pre = conn.prepareStatement(sql);
                Pre.setObject(1, tableFriend.getValueAt(index, 1));
                Pre.setObject(2, tableFriend.getValueAt(index, 2));
                Pre.setObject(3, tableFriend.getValueAt(index, 3));
                Pre.setObject(4, tableFriend.getValueAt(index, 4));
                Pre.executeUpdate();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }                                      

    private void cmdClearActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        txtName.setText("");
        txtTel.setText("");
        txtEmail.setText("");
        txtJob.setText("");
        txtSearch.setText("");
        bindData(); //Refresh JTable
    }                                      

    private void txtSearchKeyReleased(java.awt.event.KeyEvent evt) {                                    
        // TODO add your handling code here:
        String searchText = txtSearch.getText();

        try{
            if(!searchText.isEmpty()){
                bindData();
            }
        }catch(Exception e){

        }
    }                                    

    private void txtJobActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
    }                                    

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new jFrameMyFriend().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                    
    private javax.swing.JButton cmdClear;
    private javax.swing.JButton cmdDelete;
    private javax.swing.JButton cmdSave;
    private javax.swing.JButton cmdUpdate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tableFriend;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtJob;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtSearch;
    private javax.swing.JTextField txtTel;
    // End of variables declaration                  

}

MyConnect.java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package telephone;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author acer
 */
public class MyConnect {
    public static Connection getConnection(){
        try{
        Class.forName(com.mysql.jdbc.Driver.class.getName());
        return DriverManager.getConnection("jdbc:mysql://localhost/db_telephone", "root", "root");
        }catch(Exception e){
           e.printStackTrace();
        }
        return null;
    }

}