By GokiSoft.com| 10:17 18/09/2021|
Java Advanced

[Share Code] Dự án quản lý khách hàng - Java console + Java Swing (FX) - Lập trình Java nâng cao



Xây dựng 1 menu chương trình:
1. Thêm khách hàng
2. Hiển thị thông tin
3. Tìm kiếm
4. Sửa thông tin
5. Xoá
6. Thoát

-> Chuyen sang UI (Java Swing)




#BaseDAO.java


/*
 * 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.
 */
package lesson07;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class BaseDAO {
    static Connection conn = null;
    static PreparedStatement statement = null;

    static void openConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");

            conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
        } catch (SQLException ex) {
            Logger.getLogger(CustomerDAO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(BaseDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    static void closeConnection() {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ex) {
                Logger.getLogger(CustomerDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(CustomerDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}


#Config.java


/*
 * 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.
 */
package lesson07;

/**
 *
 * @author Diep.Tran
 */
public interface Config {
    String DATANAME = "C2010G";
    String DB_URL = "jdbc:mysql://localhost:3306/" + DATANAME;
    String USERNAME = "root";
    String PASSWORD = "";
}


#Customer.java


/*
 * 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.
 */
package lesson07;

import java.util.Scanner;

/**
 *
 * @author Diep.Tran
 */
public class Customer {
    int id;
    String fullname, email, phoneNumber, birthday, address, password;

    public Customer() {
    }

    public Customer(int id, String fullname, String email, String phoneNumber, String birthday, String address, String password) {
        this.id = id;
        this.fullname = fullname;
        this.email = email;
        this.phoneNumber = phoneNumber;
        this.birthday = birthday;
        this.address = address;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "Customer{" + "id=" + id + ", fullname=" + fullname + ", email=" + email + ", phoneNumber=" + phoneNumber + ", birthday=" + birthday + ", address=" + address + ", password=" + password + '}';
    }
    
    public void input() {
        Scanner scan = new Scanner(System.in);
        
        System.out.println("Nhap ten: ");
        fullname = scan.nextLine();
        
        System.out.println("Nhap email: ");
        email = scan.nextLine();
        
        System.out.println("Nhap SDT: ");
        phoneNumber = scan.nextLine();
        
        System.out.println("Nhap ngay sinh: ");
        birthday = scan.nextLine();
        
        System.out.println("Nhap dia chi: ");
        address = scan.nextLine();
        
        System.out.println("Nhap mat khau: ");
        password = scan.nextLine();
    }
}


#CustomerDAO.java


/*
 * 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.
 */
package lesson07;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static lesson07.BaseDAO.statement;

/**
 *
 * @author Diep.Tran
 */
public class CustomerDAO extends BaseDAO{
    public static List<Customer> getCustomerList(String s) {
        openConnection();
        
        List<Customer> dataList = new ArrayList<>();

        try {
            String sql = "select * from customer";
            if(s != null && !s.isEmpty()) {
                sql += " where fullname like ?";
            }
            
            statement = conn.prepareStatement(sql);
            if(s != null && !s.isEmpty()) {
                statement.setString(1, s);
            }

            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                Customer c = new Customer(
                        resultSet.getInt("id"),
                        resultSet.getString("fullname"),
                        resultSet.getString("email"),
                        resultSet.getString("phone_number"),
                        resultSet.getString("birthday"),
                        resultSet.getString("address"),
                        resultSet.getString("password")
                );
                dataList.add(c);
            }
        } catch (SQLException e) {
        }
        closeConnection();
        return dataList;
    }
    
    public static Customer findById(int id) {
        openConnection();
        
        Customer c = null;

        try {
            String sql = "select * from customer where id = ?";
            
            statement = conn.prepareStatement(sql);
            statement.setInt(1, id);

            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                c = new Customer(
                        resultSet.getInt("id"),
                        resultSet.getString("fullname"),
                        resultSet.getString("email"),
                        resultSet.getString("phone_number"),
                        resultSet.getString("birthday"),
                        resultSet.getString("address"),
                        resultSet.getString("password")
                );
                break;
            }
        } catch (SQLException e) {
        }
        closeConnection();
        
        return c;
    }
    
    public static void insert(Customer customer) {
        openConnection();
        
        try {
            String sql = "insert into customer(fullname, email, phone_number, birthday, address, password) "
                    + "values(?, ?, ?, ?, ?, ?)";
            statement = conn.prepareStatement(sql);
            statement.setString(1, customer.getFullname());
            statement.setString(2, customer.getEmail());
            statement.setString(3, customer.getPhoneNumber());
            statement.setString(4, customer.getBirthday());
            statement.setString(5, customer.getAddress());
            statement.setString(6, customer.getPassword());
            
            statement.execute();
        } catch (SQLException e) {
        }
        closeConnection();
    }
    
    public static void update(Customer customer) {
        openConnection();
        
        try {
            String sql = "update customer set fullname = ?, email = ?, phone_number = ?, birthday = ?, address = ?, password = ? where id = ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, customer.getFullname());
            statement.setString(2, customer.getEmail());
            statement.setString(3, customer.getPhoneNumber());
            statement.setString(4, customer.getBirthday());
            statement.setString(5, customer.getAddress());
            statement.setString(6, customer.getPassword());
            statement.setInt(7, customer.getId());
            
            statement.execute();
        } catch (SQLException e) {
        }
        closeConnection();
    }
    
    public static void delete(int id) {
        openConnection();
        
        try {
            String sql = "delete from customer where id = ?";
            statement = conn.prepareStatement(sql);
            statement.setInt(1, id);
            
            statement.execute();
        } catch (SQLException e) {
        }
        closeConnection();
    }
}


#CustomerFrame.form


<?xml version="1.0" encoding="UTF-8" ?>

<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
  <Properties>
    <Property name="defaultCloseOperation" type="int" value="3"/>
    <Property name="title" type="java.lang.String" value="CHUONG TRINH QUAN LY KHACH HANG"/>
  </Properties>
  <SyntheticProperties>
    <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
    <SyntheticProperty name="generateCenter" type="boolean" value="false"/>
  </SyntheticProperties>
  <AuxValues>
    <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
    <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
    <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
  </AuxValues>

  <Layout>
    <DimensionLayout dim="0">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" attributes="0">
              <EmptySpace max="-2" attributes="0"/>
              <Group type="103" groupAlignment="0" attributes="0">
                  <Component id="jPanel1" max="32767" attributes="0"/>
                  <Component id="jScrollPane1" pref="647" max="32767" attributes="0"/>
              </Group>
              <EmptySpace max="-2" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
    <DimensionLayout dim="1">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" alignment="0" attributes="0">
              <EmptySpace max="-2" attributes="0"/>
              <Component id="jPanel1" min="-2" max="-2" attributes="0"/>
              <EmptySpace max="32767" attributes="0"/>
              <Component id="jScrollPane1" min="-2" pref="165" max="-2" attributes="0"/>
              <EmptySpace min="-2" pref="10" max="-2" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
  </Layout>
  <SubComponents>
    <Container class="javax.swing.JPanel" name="jPanel1">
      <Properties>
        <Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
          <Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
            <TitledBorder title="NHAP THONG TIN KHACH HANG"/>
          </Border>
        </Property>
      </Properties>

      <Layout>
        <DimensionLayout dim="0">
          <Group type="103" groupAlignment="0" attributes="0">
              <Group type="102" alignment="0" attributes="0">
                  <EmptySpace min="-2" pref="24" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="0" attributes="0">
                      <Component id="jLabel4" alignment="0" min="-2" max="-2" attributes="0"/>
                      <Component id="jLabel3" alignment="0" min="-2" max="-2" attributes="0"/>
                      <Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
                      <Component id="jLabel1" alignment="0" min="-2" max="-2" attributes="0"/>
                      <Component id="jLabel5" alignment="0" min="-2" max="-2" attributes="0"/>
                      <Component id="jLabel6" alignment="0" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace min="-2" pref="91" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="0" max="-2" attributes="0">
                      <Component id="addressTxt" pref="316" max="32767" attributes="0"/>
                      <Component id="fullnameTxt" max="32767" attributes="0"/>
                      <Component id="emailTxt" pref="316" max="32767" attributes="0"/>
                      <Component id="phoneTxt" pref="316" max="32767" attributes="0"/>
                      <Component id="birthdayTxt" pref="316" max="32767" attributes="0"/>
                      <Component id="passwordTxt" alignment="0" max="32767" attributes="0"/>
                  </Group>
                  <EmptySpace type="separate" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="0" attributes="0">
                      <Component id="saveBtn" max="32767" attributes="0"/>
                      <Component id="searchBtn" max="32767" attributes="0"/>
                      <Component id="deleteBtn" max="32767" attributes="0"/>
                  </Group>
                  <EmptySpace max="-2" attributes="0"/>
              </Group>
          </Group>
        </DimensionLayout>
        <DimensionLayout dim="1">
          <Group type="103" groupAlignment="0" attributes="0">
              <Group type="102" alignment="0" attributes="0">
                  <EmptySpace min="-2" pref="13" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="fullnameTxt" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="saveBtn" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace type="separate" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="emailTxt" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="searchBtn" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace type="separate" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="phoneTxt" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="deleteBtn" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace type="separate" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel4" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="birthdayTxt" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace type="unrelated" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel5" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="addressTxt" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace type="separate" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel6" alignment="3" min="-2" max="-2" attributes="0"/>
                      <Component id="passwordTxt" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace pref="12" max="32767" attributes="0"/>
              </Group>
          </Group>
        </DimensionLayout>
      </Layout>
      <SubComponents>
        <Component class="javax.swing.JLabel" name="jLabel1">
          <Properties>
            <Property name="text" type="java.lang.String" value="TEN KH:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JTextField" name="fullnameTxt">
        </Component>
        <Component class="javax.swing.JTextField" name="emailTxt">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel2">
          <Properties>
            <Property name="text" type="java.lang.String" value="EMAIL:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JTextField" name="phoneTxt">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel3">
          <Properties>
            <Property name="text" type="java.lang.String" value="SDT:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JTextField" name="birthdayTxt">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel4">
          <Properties>
            <Property name="text" type="java.lang.String" value="NGAY SINH:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JTextField" name="addressTxt">
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel5">
          <Properties>
            <Property name="text" type="java.lang.String" value="DIA CHI:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel6">
          <Properties>
            <Property name="text" type="java.lang.String" value="MAT KHAU:"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JPasswordField" name="passwordTxt">
        </Component>
        <Component class="javax.swing.JButton" name="saveBtn">
          <Properties>
            <Property name="text" type="java.lang.String" value="SAVE"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="saveBtnActionPerformed"/>
          </Events>
        </Component>
        <Component class="javax.swing.JButton" name="searchBtn">
          <Properties>
            <Property name="text" type="java.lang.String" value="SEARCH"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="searchBtnActionPerformed"/>
          </Events>
        </Component>
        <Component class="javax.swing.JButton" name="deleteBtn">
          <Properties>
            <Property name="text" type="java.lang.String" value="DELETE"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="deleteBtnActionPerformed"/>
          </Events>
        </Component>
      </SubComponents>
    </Container>
    <Container class="javax.swing.JScrollPane" name="jScrollPane1">
      <AuxValues>
        <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
      </AuxValues>

      <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
      <SubComponents>
        <Component class="javax.swing.JTable" name="customerTable">
          <Properties>
            <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.editors2.TableModelEditor">
              <Table columnCount="5" rowCount="0">
                <Column editable="false" title="STT" type="java.lang.Object"/>
                <Column editable="false" title="Ho &amp; Ten" type="java.lang.Object"/>
                <Column editable="false" title="SDT" type="java.lang.Object"/>
                <Column editable="false" title="Email" type="java.lang.Object"/>
                <Column editable="false" title="Dia Chi" type="java.lang.Object"/>
              </Table>
            </Property>
            <Property name="columnModel" type="javax.swing.table.TableColumnModel" editor="org.netbeans.modules.form.editors2.TableColumnModelEditor">
              <TableColumnModel selectionModel="0">
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
              </TableColumnModel>
            </Property>
            <Property name="tableHeader" type="javax.swing.table.JTableHeader" editor="org.netbeans.modules.form.editors2.JTableHeaderEditor">
              <TableHeader reorderingAllowed="true" resizingAllowed="true"/>
            </Property>
          </Properties>
        </Component>
      </SubComponents>
    </Container>
  </SubComponents>
</Form>


#CustomerFrame.java


/*
 * 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.
 */
package lesson07;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Diep.Tran
 */
public class CustomerFrame extends javax.swing.JFrame {
    DefaultTableModel tableModel;
    List<Customer> dataList = new ArrayList<>();
    Customer currentCustomer = null;
    
    /**
     * Creates new form CustomerFrame
     */
    public CustomerFrame() {
        initComponents();
        
        tableModel = (DefaultTableModel) customerTable.getModel();
        
        dataList = CustomerDAO.getCustomerList(null);
        showCustomers();
        
        customerTable.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int index = customerTable.getSelectedRow();
                currentCustomer = dataList.get(index);
                
                fullnameTxt.setText(currentCustomer.getFullname());
                emailTxt.setText(currentCustomer.getEmail());
                addressTxt.setText(currentCustomer.getAddress());
                phoneTxt.setText(currentCustomer.getPhoneNumber());
                birthdayTxt.setText(currentCustomer.getBirthday());
                passwordTxt.setText(currentCustomer.getPassword());
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
    }
    
    private void showCustomers() {
        tableModel.setRowCount(0);
        
        for (Customer customer : dataList) {
            tableModel.addRow(new Object[] {
                tableModel.getRowCount() + 1,
                customer.getFullname(),
                customer.getPhoneNumber(),
                customer.getEmail(),
                customer.getAddress()
            });
        }
    }

    /**
     * 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">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        fullnameTxt = new javax.swing.JTextField();
        emailTxt = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        phoneTxt = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        birthdayTxt = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        addressTxt = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        passwordTxt = new javax.swing.JPasswordField();
        saveBtn = new javax.swing.JButton();
        searchBtn = new javax.swing.JButton();
        deleteBtn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        customerTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("CHUONG TRINH QUAN LY KHACH HANG");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("NHAP THONG TIN KHACH HANG"));

        jLabel1.setText("TEN KH:");

        jLabel2.setText("EMAIL:");

        jLabel3.setText("SDT:");

        jLabel4.setText("NGAY SINH:");

        jLabel5.setText("DIA CHI:");

        jLabel6.setText("MAT KHAU:");

        saveBtn.setText("SAVE");
        saveBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveBtnActionPerformed(evt);
            }
        });

        searchBtn.setText("SEARCH");
        searchBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchBtnActionPerformed(evt);
            }
        });

        deleteBtn.setText("DELETE");
        deleteBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteBtnActionPerformed(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()
                .addGap(24, 24, 24)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addGap(91, 91, 91)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(addressTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
                    .addComponent(fullnameTxt)
                    .addComponent(emailTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
                    .addComponent(phoneTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
                    .addComponent(birthdayTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
                    .addComponent(passwordTxt))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(saveBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(searchBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(deleteBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(fullnameTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(saveBtn))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(emailTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchBtn))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(phoneTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(deleteBtn))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(birthdayTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(addressTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(passwordTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(12, Short.MAX_VALUE))
        );

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

            },
            new String [] {
                "STT", "Ho & Ten", "SDT", "Email", "Dia Chi"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(customerTable);
        if (customerTable.getColumnModel().getColumnCount() > 0) {
            customerTable.getColumnModel().getColumn(0).setResizable(false);
            customerTable.getColumnModel().getColumn(1).setResizable(false);
            customerTable.getColumnModel().getColumn(2).setResizable(false);
            customerTable.getColumnModel().getColumn(3).setResizable(false);
            customerTable.getColumnModel().getColumn(4).setResizable(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()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 647, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
        // TODO add your handling code here:
        String fullname = fullnameTxt.getText();
        String email = emailTxt.getText();
        String birthday = birthdayTxt.getText();
        String address = addressTxt.getText();
        String phoneNumber = phoneTxt.getText();
        String password = passwordTxt.getText();
        
        if(currentCustomer != null) {
            currentCustomer.setFullname(fullname);
            currentCustomer.setEmail(email);
            currentCustomer.setAddress(address);
            currentCustomer.setPhoneNumber(phoneNumber);
            currentCustomer.setBirthday(birthday);
            currentCustomer.setPassword(password);
            CustomerDAO.update(currentCustomer);
            currentCustomer = null;
        } else {
            Customer c = new Customer(0, fullname, email, phoneNumber, birthday, address, password);
            CustomerDAO.insert(c);
            dataList = CustomerDAO.getCustomerList(null);
        }
        showCustomers();
        
        resetData();
    }//GEN-LAST:event_saveBtnActionPerformed

    private void resetData() {
        fullnameTxt.setText("");
        emailTxt.setText("");
        birthdayTxt.setText("");
        addressTxt.setText("");
        phoneTxt.setText("");
        passwordTxt.setText("");
    }
    
    private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchBtnActionPerformed
        // TODO add your handling code here:
        String s = JOptionPane.showInputDialog("Nhap ten khach hang can tim kiem");
        if(s.isEmpty()) {
            dataList = CustomerDAO.getCustomerList(null);
        } else {
            dataList = CustomerDAO.getCustomerList("%" + s + "%");
        }
        
        showCustomers();
    }//GEN-LAST:event_searchBtnActionPerformed

    private void deleteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteBtnActionPerformed
        // TODO add your handling code here:
        if(currentCustomer == null) {
            JOptionPane.showMessageDialog(rootPane, "Chon khach hang can xoa!!!");
            return;
        }
        int option = JOptionPane.showConfirmDialog(rootPane, "Ban chac chan muon xoa khach hang nay khong?");
        System.out.println("option: " + option);
        if(option == 0) {
            CustomerDAO.delete(currentCustomer.getId());
            dataList.remove(currentCustomer);
        }
        currentCustomer = null;
        showCustomers();
        resetData();
    }//GEN-LAST:event_deleteBtnActionPerformed

    /**
     * @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 ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CustomerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CustomerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CustomerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CustomerFrame.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 CustomerFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField addressTxt;
    private javax.swing.JTextField birthdayTxt;
    private javax.swing.JTable customerTable;
    private javax.swing.JButton deleteBtn;
    private javax.swing.JTextField emailTxt;
    private javax.swing.JTextField fullnameTxt;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPasswordField passwordTxt;
    private javax.swing.JTextField phoneTxt;
    private javax.swing.JButton saveBtn;
    private javax.swing.JButton searchBtn;
    // End of variables declaration//GEN-END:variables
}


#Main.java


/*
 * 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.
 */
package lesson07;

import java.util.List;

/**
 *
 * @author Diep.Tran
 */
public class Main {
    public static void main(String[] args) {
        List<Customer> dataList = CustomerDAO.getCustomerList(null);
        for (Customer customer : dataList) {
            System.out.println(customer);
        }
        
        //INSERT
//        System.out.println("Nhap du lieu vao database: ");
//        Customer customer = new Customer();
//        customer.input();
//        CustomerDAO.insert(customer);
        //UPDATE
//        System.out.println("Sua thong tin khach hang");
//        Customer c = dataList.get(0);
//        c.input();
//        CustomerDAO.update(c);
        //DELETE
//        CustomerDAO.delete(dataList.get(0).getId());
//        System.out.println("Xoa thanh cong");
    }
}


#Test.java


/*
 * 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.
 */
package lesson07;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Diep.Tran
 */
public class Test {
    static InputStreamReader reader = new InputStreamReader(System.in);
    static BufferedReader bufferedReader = new BufferedReader(reader);
        
    public static void main(String[] args) throws IOException {
        int choose;
        
        do {
            showMenu();
            choose = Integer.parseInt(bufferedReader.readLine());
            
            switch(choose) {
                case 1:
                    input();
                    break;
                case 2:
                    display();
                    break;
                case 3:
                    searchByName();
                    break;
                case 4:
                    updateCustomer();
                    break;
                case 5:
                    deleteCustomer();
                    break;
                case 6:
                    System.out.println("Thoat!!!");
                    break;
                default:
                    System.out.println("Nhap sai!!!");
                    break;
            }
        } while(choose != 6);
        
        if(reader != null) {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if(bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    static void input() {
        System.out.println("Nhap thong tin khach hang moi.");
        Customer c = new Customer();
        c.input();

        CustomerDAO.insert(c);
    }
    
    static void display() {
        List<Customer> list = CustomerDAO.getCustomerList(null);
        System.out.println("Danh sach khach hang");

        for (Customer customer : list) {
            System.out.println(customer);
        }
    }
    
    static void searchByName() {
        try {
            System.out.println("Nhap ten can tim kiem: ");
            String searchName = bufferedReader.readLine();
            
            List<Customer> list = CustomerDAO.getCustomerList("%" + searchName + "%");
            System.out.println("Danh sach khach hang");

            for (Customer customer : list) {
                System.out.println(customer);
            }
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    static void showMenu() {
        System.out.println("1. Nhap thong tin");
        System.out.println("2. Hien thi");
        System.out.println("3. Tim kiem");
        System.out.println("4. Sua thong tin");
        System.out.println("5. Xoa");
        System.out.println("6. Thoat");
        System.out.println("Chon: ");
    }

    private static void updateCustomer() {
        try {
            reader = new InputStreamReader(System.in);
            bufferedReader = new BufferedReader(reader);
            
            System.out.println("Nhap ID can sua thong tin: ");
            int id = Integer.parseInt(bufferedReader.readLine());
            Customer c = CustomerDAO.findById(id);
            
            c.input();
            
            CustomerDAO.update(c);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static void deleteCustomer() {
        try {
            System.out.println("Nhap ID can xoa: ");
            int id = Integer.parseInt(bufferedReader.readLine());
            
            CustomerDAO.delete(id);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Cấu hình Build

pom.xml



<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.aptech</groupId>
    <artifactId>C2009G</artifactId>
    <packaging>jar</packaging>
    <version>1.0</version>
    <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
              <execution>
                <goals>
                  <goal>shade</goal>
                </goals>
                <configuration>
                  <transformers>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                      <manifestEntries>
                        <Main-Class>lesson07.CustomerFrame</Main-Class>
                        <X-Compile-Source-JDK>${maven.compile.source}</X-Compile-Source-JDK>
                        <X-Compile-Target-JDK>${maven.compile.target}</X-Compile-Target-JDK>
                      </manifestEntries>
                    </transformer>
                  </transformers>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.8</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20210307</version>
        </dependency>

    </dependencies>
</project>


Run.bat



java -jar C2009G-1.0.jar





Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)