IMG-LOGO
×

Tài Liệu Học

Khoá học lập trình Java Core nâng cao

Exception & Collection

[Video] Tìm hiểu exception + debug + package - lập trình Java Nâng Cao [Video] Tìm hiểu collections, Sets, Maps và Generic - lập trình java nâng cao [Video] Chương trình quản lý sinh viên bằng HashMap - Java Advanced

File

[Video] Hướng dẫn đọc ghi file FileInputStream, FileOutputStream, ObjectInputStream trong java - lập trình java nâng cao [Video] Bài tập quản lý sách & lưu thông tin trên Files [Video] File - Quản lý thông tin sinh viên [Video] Quản lý thông tin sinh & lưu object file - Java nâng cao [Video] Viết ứng dụng WinRar | WinZip | 7Zip bằng Java - Nén file Java & giải nén file Java - Khoá học Java [Video] Bài tập quản lý bán vé máy bay - java nâng cao

Thread

[Video] Phân tích quản lý ứng dụng trong HĐH (Window, Mac, Linux)-Phân tích Game đa luồng Java [Video] Tìm hiểu Thread - Đồng bộ Thread - lập trình java nâng cao - Bổ sung thêm lớp học mới. [Video] Giải thích synchronized + Lap trinh Java nang cao [Video] Thread thực hiện in ngẫu nhiên các số nguyên và ký tự - Phần 1 [Video] Thread thực hiện in ngẫu nhiên các số nguyên và ký tự & Đông bộ thread + wait notify + synchronized + Java nâng cao - Phần 2 [Video] Synchronized 2 Thread - Bài tập mảng tên + địa chỉ - Java nâng cao [Video] Bài tập ôn luyện tổng hợp File, OOP, Thread trong java [Video] Sử dụng MultiThreading sinh ký tự a-zA-Z trong java

CSDL

[Video] Kết nối MySQL trong java swing JDBC trong java - lập trình java nâng cao [Video] Kết nối CSDL bằng java swing phần 1 - lập trình java nâng cao [Video] Kết nối CSDL bằng java swing phần 2 - lập trình java nâng cao [Video] Chương trình quản lý thư viện Java + XML Java + CSDL Java- SQL Java [Video] Phần mềm quản lý sinh viên MySQL + Java - Chương trình quản lý sinh viên MySQL + Java - Lập Trình Java [Video] Bài Tập Quản Lý Sinh Viên - CSDL - Java Swing [Video] Chương trình quản lý sản phẩm - quản lý tin tức - quản lý bán hàng - Lập trình Java [Video] Chức năng register & login + CSDL - Lập trình Java nâng cao - Phần 1 [Video] Hướng dẫn sử dụng Persistence Java - Kết nối database Java - MySQL Java nâng cao

Design Pattern & Đa Ngôn Ngữ

[Video] Design Pattern lập trình java nâng cao - lập trình java nâng cao

XML & JSON & CSDL

[Video] C1 > Chương trình quản lý sinh viên Java + Import/Export JSON + File - Lập Trình Java [Video] C2 > Chương trình quản lý sinh viên Java + Import/Export JSON + File - Lập Trình Java

Ôn Tập Tổng Quát & Exmination

[Video] Bài tập - Chường trình quản lý sở thú - Lập trình Java - Lập trình Java nâng cao - Phần 1 [Video] Bài tập - Chường trình quản lý sở thú - Lập trình Java - Lập trình Java nâng cao - Phần 2




Trang Chủ Java Advanced Bài Tập Quản Lý Sinh Viên - CSDL - Java Swing

Bài Tập Quản Lý Sinh Viên - CSDL - Java Swing

by GokiSoft.com - 20:01 06/11/2021 15,101 Lượt Xem

Xây dựng chương trình như hình sau

Yêu cầu :

- Khi người dùng click save -> add danh sách sinh viên vào bảng quản lý

- Khi người dùng click vào reset -> Xoá dữ liệu trong form nhập

- Khi người dùng click vào delete -> Xoá sinh viên đang được lựa chọn trong bảng quản lý

- Khi người dùng click vào find -> Hiển thị lên dialog nhập tên sinh viên cần tìm kiếm -> Hiển thị lại dữ liệu sinh viên tìm thấy trong bảng, nếu ko tìm thấy sinh viên nào thì hiển thị dialog thông báo ko tìm thấy bất kỳ sinh viên nào.

Bình luận



Chia sẻ từ lớp học

Nguyễn Tiến Đạt [T2008A]

Ngày viết: 09:56 24/03/2021


#Student.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 Java2.lesson5.QuanLySinhVien;

/**
 *
 * @author MyPC
 */
public class Student {
    String name, gender, email, phoneNumber;
    int age;

    public Student() {
    }

    public Student(String name, String gender, String email, String phoneNumber, int age) {
        this.name = name;
        this.gender = gender;
        this.email = email;
        this.phoneNumber = phoneNumber;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", gender=" + gender + ", email=" + email + ", phoneNumber=" + phoneNumber + ", age=" + age + '}';
    }
    
}


#StudentFrame.form


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

<Form version="1.5" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
  <Properties>
    <Property name="defaultCloseOperation" type="int" value="3"/>
  </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" alignment="0" attributes="0">
              <EmptySpace min="-2" pref="67" max="-2" attributes="0"/>
              <Group type="103" groupAlignment="0" max="-2" attributes="0">
                  <Component id="jScrollPane1" max="32767" attributes="0"/>
                  <Component id="jPanel1" max="32767" attributes="0"/>
              </Group>
              <EmptySpace pref="67" max="32767" 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="40" max="-2" attributes="0"/>
              <Component id="jPanel1" min="-2" max="-2" attributes="0"/>
              <EmptySpace min="-2" pref="32" max="-2" attributes="0"/>
              <Component id="jScrollPane1" min="-2" pref="208" max="-2" attributes="0"/>
              <EmptySpace pref="46" max="32767" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
  </Layout>
  <SubComponents>
    <Container class="javax.swing.JPanel" name="jPanel1">
      <Properties>
        <Property name="background" type="java.awt.Color" editor="org.netbeans.beaninfo.editors.ColorEditor">
          <Color blue="cc" green="cc" red="cc" type="rgb"/>
        </Property>
        <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 sinh vien">
              <Font PropertyName="font" name="Tahoma" size="18" style="0"/>
              <Color PropertyName="color" blue="0" green="cc" red="33" type="rgb"/>
            </TitledBorder>
          </Border>
        </Property>
      </Properties>

      <Layout>
        <DimensionLayout dim="0">
          <Group type="103" groupAlignment="0" attributes="0">
              <Group type="102" alignment="0" attributes="0">
                  <EmptySpace min="44" pref="44" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="0" attributes="0">
                      <Component id="jLabel1" alignment="0" min="-2" pref="100" max="-2" attributes="0"/>
                      <Component id="jLabel2" alignment="0" min="-2" pref="100" max="-2" attributes="0"/>
                      <Component id="jLabel3" alignment="0" min="-2" pref="100" max="-2" attributes="0"/>
                      <Component id="jLabel4" alignment="0" min="-2" pref="100" max="-2" attributes="0"/>
                      <Component id="jLabel5" alignment="0" min="-2" pref="117" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace min="-2" pref="27" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="0" attributes="0">
                      <Group type="102" attributes="0">
                          <Component id="btnSave" min="-2" pref="70" max="-2" attributes="0"/>
                          <EmptySpace min="-2" pref="28" max="-2" attributes="0"/>
                          <Component id="btnReset" min="-2" pref="67" max="-2" attributes="0"/>
                          <EmptySpace min="-2" pref="31" max="-2" attributes="0"/>
                          <Component id="btnDelete" min="-2" pref="67" max="-2" attributes="0"/>
                          <EmptySpace min="-2" pref="34" max="-2" attributes="0"/>
                          <Component id="btnFind" min="-2" pref="67" max="-2" attributes="0"/>
                      </Group>
                      <Group type="103" groupAlignment="0" max="-2" attributes="0">
                          <Component id="genderBox" min="-2" max="-2" attributes="0"/>
                          <Component id="name" max="32767" attributes="0"/>
                          <Component id="age" alignment="0" max="32767" attributes="0"/>
                          <Component id="email" max="32767" attributes="0"/>
                          <Component id="phoneNumber" pref="470" max="32767" attributes="0"/>
                      </Group>
                  </Group>
                  <EmptySpace pref="99" max="32767" 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="33" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel1" alignment="3" min="-2" pref="28" max="-2" attributes="0"/>
                      <Component id="name" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace min="-2" pref="33" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel2" alignment="3" min="-2" pref="28" max="-2" attributes="0"/>
                      <Component id="genderBox" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace min="-2" pref="33" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel3" alignment="3" min="-2" pref="28" max="-2" attributes="0"/>
                      <Component id="age" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace min="-2" pref="33" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel4" alignment="3" min="-2" pref="28" max="-2" attributes="0"/>
                      <Component id="email" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace min="-2" pref="33" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="3" attributes="0">
                      <Component id="jLabel5" alignment="3" min="-2" pref="28" max="-2" attributes="0"/>
                      <Component id="phoneNumber" alignment="3" min="-2" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace min="-2" pref="25" max="-2" attributes="0"/>
                  <Group type="103" groupAlignment="0" attributes="0">
                      <Component id="btnSave" min="-2" pref="37" max="-2" attributes="0"/>
                      <Component id="btnReset" min="-2" pref="37" max="-2" attributes="0"/>
                      <Component id="btnDelete" min="-2" pref="37" max="-2" attributes="0"/>
                      <Component id="btnFind" min="-2" pref="37" max="-2" attributes="0"/>
                  </Group>
                  <EmptySpace pref="32" max="32767" attributes="0"/>
              </Group>
          </Group>
        </DimensionLayout>
      </Layout>
      <SubComponents>
        <Component class="javax.swing.JLabel" name="jLabel1">
          <Properties>
            <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor">
              <Font name="Tahoma" size="13" style="1"/>
            </Property>
            <Property name="text" type="java.lang.String" value="Full Name :"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel2">
          <Properties>
            <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor">
              <Font name="Tahoma" size="13" style="1"/>
            </Property>
            <Property name="text" type="java.lang.String" value="Gender :"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel3">
          <Properties>
            <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor">
              <Font name="Tahoma" size="13" style="1"/>
            </Property>
            <Property name="text" type="java.lang.String" value="Age :"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel4">
          <Properties>
            <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor">
              <Font name="Tahoma" size="13" style="1"/>
            </Property>
            <Property name="text" type="java.lang.String" value="Email :"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JLabel" name="jLabel5">
          <Properties>
            <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor">
              <Font name="Tahoma" size="13" style="1"/>
            </Property>
            <Property name="text" type="java.lang.String" value="Phone Number :"/>
          </Properties>
        </Component>
        <Component class="javax.swing.JTextField" name="name">
        </Component>
        <Component class="javax.swing.JComboBox" name="genderBox">
          <Properties>
            <Property name="model" type="javax.swing.ComboBoxModel" editor="org.netbeans.modules.form.editors2.ComboBoxModelEditor">
              <StringArray count="2">
                <StringItem index="0" value="Nam"/>
                <StringItem index="1" value="Nu"/>
              </StringArray>
            </Property>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="genderBoxActionPerformed"/>
          </Events>
          <AuxValues>
            <AuxValue name="JavaCodeGenerator_TypeParameters" type="java.lang.String" value="&lt;String&gt;"/>
          </AuxValues>
        </Component>
        <Component class="javax.swing.JTextField" name="age">
        </Component>
        <Component class="javax.swing.JTextField" name="email">
        </Component>
        <Component class="javax.swing.JTextField" name="phoneNumber">
        </Component>
        <Component class="java.awt.Button" name="btnSave">
          <Properties>
            <Property name="label" type="java.lang.String" value="Save"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnSaveActionPerformed"/>
          </Events>
        </Component>
        <Component class="java.awt.Button" name="btnReset">
          <Properties>
            <Property name="label" type="java.lang.String" value="Reset"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnResetActionPerformed"/>
          </Events>
        </Component>
        <Component class="java.awt.Button" name="btnDelete">
          <Properties>
            <Property name="label" type="java.lang.String" value="Delete"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnDeleteActionPerformed"/>
          </Events>
        </Component>
        <Component class="java.awt.Button" name="btnFind">
          <Properties>
            <Property name="label" type="java.lang.String" value="Find"/>
          </Properties>
          <Events>
            <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnFindActionPerformed"/>
          </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="tblStudent">
          <Properties>
            <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.editors2.TableModelEditor">
              <Table columnCount="6" rowCount="0">
                <Column editable="true" title="No" type="java.lang.Object"/>
                <Column editable="true" title="Full Name" type="java.lang.Object"/>
                <Column editable="true" title="Gender" type="java.lang.Object"/>
                <Column editable="true" title="Age" type="java.lang.Object"/>
                <Column editable="true" title="Email" type="java.lang.Object"/>
                <Column editable="true" title="Phone Number" 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="true">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true">
                  <Title/>
                  <Editor/>
                  <Renderer/>
                </Column>
                <Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="true">
                  <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>


#StudentFrame.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 Java2.lesson5.QuanLySinhVien;

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

/**
 *
 * @author MyPC
 */
public class StudentFrame extends javax.swing.JFrame {
    ArrayList<Student> studentList = new ArrayList<>();
    DefaultTableModel tableModel;
    int index = -1;
    /**
     * Creates new form StudentFrame
     */
    public StudentFrame() {
        initComponents();
        tableModel = (DefaultTableModel) tblStudent.getModel();
        tblStudent.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                index = tblStudent.getSelectedRow();
                Student std = studentList.get(index);
                name.setText(std.getName());
                genderBox.setSelectedItem(std.getGender());
                age.setText(String.valueOf(std.getAge()));
                email.setText(std.getEmail());
                phoneNumber.setText(std.getPhoneNumber());
            }

            @Override
            public void mousePressed(MouseEvent e) {
                
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                
            }

            @Override
            public void mouseExited(MouseEvent e) {
                
            }
        });
    }

    /**
     * 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();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        name = new javax.swing.JTextField();
        genderBox = new javax.swing.JComboBox<>();
        age = new javax.swing.JTextField();
        email = new javax.swing.JTextField();
        phoneNumber = new javax.swing.JTextField();
        btnSave = new java.awt.Button();
        btnReset = new java.awt.Button();
        btnDelete = new java.awt.Button();
        btnFind = new java.awt.Button();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblStudent = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(204, 204, 204));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Nhap thong tin sinh vien", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 18), new java.awt.Color(51, 204, 0))); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel1.setText("Full Name :");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel2.setText("Gender :");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel3.setText("Age :");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel4.setText("Email :");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel5.setText("Phone Number :");

        genderBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Nam", "Nu" }));
        genderBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                genderBoxActionPerformed(evt);
            }
        });

        btnSave.setLabel("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnReset.setLabel("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        btnDelete.setLabel("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnFind.setLabel("Find");
        btnFind.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFindActionPerformed(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(44, 44, 44)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31)
                        .addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(34, 34, 34)
                        .addComponent(btnFind, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(genderBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(name)
                        .addComponent(age)
                        .addComponent(email)
                        .addComponent(phoneNumber, javax.swing.GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE)))
                .addContainerGap(99, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(genderBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(age, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(phoneNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnFind, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(32, Short.MAX_VALUE))
        );

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

            },
            new String [] {
                "No", "Full Name", "Gender", "Age", "Email", "Phone Number"
            }
        ));
        jScrollPane1.setViewportView(tblStudent);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(67, 67, 67)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(67, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(46, Short.MAX_VALUE))
        );

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

    private void genderBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_genderBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_genderBoxActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // TODO add your handling code here:
        Student student = new Student();
        student.name = name.getText();
        student.age = Integer.parseInt(age.getText());
        student.gender = genderBox.getSelectedItem().toString();
        student.email = email.getText();
        student.phoneNumber = phoneNumber.getText();
        studentList.add(student);
        showData();
        btnResetActionPerformed(evt);
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        // TODO add your handling code here:
        name.setText("");
        genderBox.setSelectedItem("Nam");
        age.setText("");
        email.setText("");
        phoneNumber.setText("");
    }//GEN-LAST:event_btnResetActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
        if(index >= 0){
            int option = JOptionPane.showConfirmDialog(rootPane, "Ban co chac chan muon xoa khong?");
            if(option != 0 ) return;
            studentList.remove(index);
            showData();
            index = -1;
        }else{
            JOptionPane.showMessageDialog(rootPane, "Khong co lua chon nao de xoa");
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFindActionPerformed
        // TODO add your handling code here:
        String search = JOptionPane.showInputDialog(rootPane,"Nhap ten can tim kiem");
        if(search.isEmpty()){
            showData();
            return;
        }
        int check = 0;
        tableModel.setRowCount(0);
        for (Student student : studentList) {
            if(student.getName().contains(search)){
                tableModel.addRow(new Object[]{tableModel.getRowCount(),student.getName(),
                    student.getGender(),student.getAge(),student.getEmail(),student.getPhoneNumber()});
                check++;
            }
        }
        if(check == 0){
            JOptionPane.showMessageDialog(rootPane, "Khong co du lieu can tim kiem");
            showData();
        }
    }//GEN-LAST:event_btnFindActionPerformed

    public void showData(){
        tableModel.setRowCount(0);
        for (Student student : studentList) {
            tableModel.addRow(new Object[]{tableModel.getRowCount(),student.getName(),
                student.getGender(),student.getAge(),student.getEmail(),student.getPhoneNumber()});
        }
    }
    /**
     * @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(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(StudentFrame.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 StudentFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField age;
    private java.awt.Button btnDelete;
    private java.awt.Button btnFind;
    private java.awt.Button btnReset;
    private java.awt.Button btnSave;
    private javax.swing.JTextField email;
    private javax.swing.JComboBox<String> genderBox;
    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.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField name;
    private javax.swing.JTextField phoneNumber;
    private javax.swing.JTable tblStudent;
    // End of variables declaration//GEN-END:variables
}


vuong huu phu [T2008A]

Ngày viết: 20:42 23/03/2021



/*
 * 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 javaapplication46;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Admin
 */
public class NewJFrame extends javax.swing.JFrame {

    DefaultTableModel tablemodel;
    List<Student> stdlist = new ArrayList<>();

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
        tablemodel = (DefaultTableModel) jTable1.getModel();
        showstd();
    }

    private void showstd() {
        stdlist = Studentmdf.Hienthi();
        tablemodel.setRowCount(0);
        stdlist.forEach((s) -> {
            tablemodel.addRow(new Object[]{tablemodel.getRowCount() + 1,
                s.getFullname(),
                s.getGender(),
                s.getAge(),
                s.getEmail(),
                s.getPhonenumber()
            });
        });
    }

    /**
     * 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() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox<>();
        Save = new javax.swing.JButton();
        Reset = new javax.swing.JButton();
        Delete = new javax.swing.JButton();
        Find = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(204, 255, 204));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Nhap thong tin sinh vien ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N

        jLabel1.setText("Gender");

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

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

        jLabel2.setText("Full name");

        jLabel3.setText("Email");

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

        jLabel4.setText("Age");

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

        jLabel5.setText("Phone number");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Nam", "Nu", "Khac" }));

        Save.setText("Save");
        Save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveActionPerformed(evt);
            }
        });

        Reset.setText("Reset");
        Reset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetActionPerformed(evt);
            }
        });

        Delete.setText("Delete");
        Delete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteActionPerformed(evt);
            }
        });

        Find.setText("Find");
        Find.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FindActionPerformed(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()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 484, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 484, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 2, Short.MAX_VALUE)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(44, 44, 44)
                        .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 484, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 484, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(43, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(63, 63, 63)
                .addComponent(Save)
                .addGap(18, 18, 18)
                .addComponent(Reset)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(Delete)
                .addGap(18, 18, 18)
                .addComponent(Find, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(60, 60, 60)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Save)
                    .addComponent(Delete)
                    .addComponent(Find)
                    .addComponent(Reset))
                .addContainerGap(31, Short.MAX_VALUE))
        );

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

            },
            new String [] {
                "Id", "Full name", "Gender", "Age", "Email", "Phone number"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

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

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

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

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

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

    private void SaveActionPerformed(java.awt.event.ActionEvent evt) {                                     
        String fullname = jTextField4.getText();
        String gender = jComboBox1.getSelectedItem().toString();
        int age = Integer.parseInt(jTextField2.getText());
        String email = jTextField1.getText();
        String phone = jTextField5.getText();

        Student std = new Student(fullname, gender, email, phone, age);
        Studentmdf.Save(std);
        showstd();
    }                                    

    private void ResetActionPerformed(java.awt.event.ActionEvent evt) {                                      
        jTextField4.setText("");
        jComboBox1.setSelectedIndex(0);
        jTextField2.setText("");
        jTextField1.setText("");
        jTextField5.setText("");

    }                                     

    private void DeleteActionPerformed(java.awt.event.ActionEvent evt) {                                       
int slindex = jTable1.getSelectedRow();
        if (slindex >0) {
            Student std = stdlist.get(slindex);
            int lc = JOptionPane.showConfirmDialog(this,"Ban co muon xoa sinh vien nay khong !!!");
            if (lc ==0 ) {
                Studentmdf.Delete(std.getId());
                showstd();
            }
        }
    }                                      

    private void FindActionPerformed(java.awt.event.ActionEvent evt) {                                     
      String nhap = JOptionPane.showInputDialog(this,"Hay nhap thong tin sinh vien can tim ");
        if (nhap.length() > 0) {
            stdlist = Studentmdf.Find(nhap);
           tablemodel.setRowCount(0);
        stdlist.forEach((s) -> {
            tablemodel.addRow(new Object[]{tablemodel.getRowCount() + 1,
                s.getFullname(),
                s.getGender(),
                s.getAge(),
                s.getEmail(),
                s.getPhonenumber()
            });
        });
        }
    }                                    

    /**
     * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new NewJFrame().setVisible(true);
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton Delete;
    private javax.swing.JButton Find;
    private javax.swing.JButton Reset;
    private javax.swing.JButton Save;
    private javax.swing.JComboBox<String> jComboBox1;
    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.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    // End of variables declaration                   
}



/*
 * 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 javaapplication46;

/**
 *
 * @author Admin
 */
public class Student {
    int id;
    String fullname,gender,email,phonenumber;
    int age;

    public Student() {
    }

    public Student(int id, String fullname, String gender, String email, String phonenumber, int age) {
        this.id = id;
        this.fullname = fullname;
        this.gender = gender;
        this.email = email;
        this.phonenumber = phonenumber;
        this.age = age;
    }

    public Student(String fullname, String gender, String email, String phonenumber, int age) {
        this.fullname = fullname;
        this.gender = gender;
        this.email = email;
        this.phonenumber = phonenumber;
        this.age = age;
    }

    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 getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

}



/*
 * 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 javaapplication46;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Admin
 */
public class Studentmdf {

    public static List<Student> Hienthi() {
        ArrayList<Student> stdlist = new ArrayList<>();
        Connection connection = null;
        Statement statement = null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/quan_li_sv_jv_1", "root", "");
            String sql = ("select * from ql_sinhvien");
            statement = connection.createStatement();
            ResultSet result = statement.executeQuery(sql);
            while (result.next()) {
                Student std = new Student(result.getInt("id"),
                        result.getString("fullname"),
                        result.getString("gender"),
                        result.getString("email"),
                        result.getString("phonenumber"),
                        result.getInt("age"));
                stdlist.add(std);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return stdlist;
    }

    public static void Save(Student std) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/quan_li_sv_jv_1", "root", "");
            String sql = ("insert into ql_sinhvien(fullname,gender,age,email,phonenumber) values(?,?,?,?,?)");
            statement = connection.prepareCall(sql);
            statement.setString(1, std.getFullname());
            statement.setString(2, std.getGender());
            statement.setInt(3, std.getAge());
            statement.setString(4, std.getEmail());
            statement.setString(5, std.getPhonenumber());
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public static void Delete(int id) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/quan_li_sv_jv_1", "root", "");
            String sql = ("delete from ql_sinhvien where id = ? ");
            statement = connection.prepareCall(sql);
            statement.setInt(1, id);
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
     public static List<Student> Find(String name) {
        ArrayList<Student> stdlist = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/quan_li_sv_jv_1", "root", "");
            String sql = ("select * from ql_sinhvien where fullname = ? ");
             statement = connection.prepareCall(sql);
            statement.setString(1,name);
            ResultSet result = statement.executeQuery();
            while (result.next()) {
                Student std = new Student(result.getInt("id"),
                        result.getString("fullname"),
                        result.getString("gender"),
                        result.getString("email"),
                        result.getString("phonenumber"),
                        result.getInt("age"));
                stdlist.add(std);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Studentmdf.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return stdlist;
    }
}


Ngô Quang Huy [C1907L]

Ngày viết: 16:38 29/05/2020



/*
 * 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 May27SQL;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Administrator
 */
public class Main extends javax.swing.JFrame {
    static DefaultTableModel tblModel;
    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
        tblModel = (DefaultTableModel) tableSQL.getModel();
    }
    
    public static void addDatabase(){
        for (int i = tblModel.getRowCount() - 1; i >= 0; i--) {
            tblModel.removeRow(i);
        }
        Connection connect =null;
        PreparedStatement statement = null;
        try {
            connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/bt?serverTimezone=UTC","root","");
            String query = "select * from teacher";
            statement = connect.prepareCall(query);

            ResultSet rs = statement.executeQuery(query);
            while(rs.next()){
                tblModel.addRow(new Object[]{tblModel.getRowCount()+1,rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5)});
            }
            rs.close();
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
            if(connect!=null){
                try {
                    connect.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    /**
     * 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() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        fullnameText = new javax.swing.JTextField();
        ageText = new javax.swing.JTextField();
        emailText = new javax.swing.JTextField();
        phoneText = new javax.swing.JTextField();
        genderText = new javax.swing.JComboBox<>();
        saveBtt = new javax.swing.JButton();
        resetBtt = new javax.swing.JButton();
        deleteBtt = new javax.swing.JButton();
        findBtt = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableSQL = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Nhap thong tin sinh vien"));

        jLabel1.setText("Full Name :");

        jLabel2.setText("Gender :");

        jLabel3.setText("Age :");

        jLabel4.setText("Email :");

        jLabel5.setText("Phone Number :");

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

        genderText.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Nam", "Nu" }));

        saveBtt.setText("Save");
        saveBtt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveBttActionPerformed(evt);
            }
        });

        resetBtt.setText("Reset");
        resetBtt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetBttActionPerformed(evt);
            }
        });

        deleteBtt.setText("Delete");
        deleteBtt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteBttActionPerformed(evt);
            }
        });

        findBtt.setText("Find");
        findBtt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                findBttActionPerformed(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()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(genderText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(fullnameText)
                            .addComponent(ageText)
                            .addComponent(emailText)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(saveBtt)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(resetBtt)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(deleteBtt)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(findBtt)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(phoneText))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(fullnameText, 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(jLabel2)
                    .addComponent(genderText, 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(jLabel3)
                    .addComponent(ageText, 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(jLabel4)
                    .addComponent(emailText, 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(jLabel5)
                    .addComponent(phoneText, 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(saveBtt)
                    .addComponent(resetBtt)
                    .addComponent(deleteBtt)
                    .addComponent(findBtt))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

            },
            new String [] {
                "No", "Full Name", "Gender", "Age", "Email", "Phone Number"
            }
        ));
        jScrollPane1.setViewportView(tableSQL);

        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)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 439, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, 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)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(24, Short.MAX_VALUE))
        );

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

    private void saveBttActionPerformed(java.awt.event.ActionEvent evt) {                                        
        
        String fullname = fullnameText.getText();
        String age = ageText.getText();
        String email = emailText.getText();
        String phone = phoneText.getText();
        String gender = genderText.getSelectedItem().toString();
        if(fullname.isEmpty()||age.isEmpty()||email.isEmpty()||phone.isEmpty()){
            JOptionPane.showMessageDialog(rootPane, "Please insert all field!");
            return;
        }
        tblModel.addRow(new Object[]{tblModel.getRowCount()+1,fullname,gender,age,email,phone});
        
        Connection connect =null;
        PreparedStatement statement = null;
        try {
            connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/bt?serverTimezone=UTC","root","");
            String query = "insert into teacher(fullname,gender,age,email,phone) values (?,?,?,?,?)";
            statement = connect.prepareCall(query);
            statement.setString(1, fullname);
            statement.setString(2, gender);
            statement.setString(3, age);
            statement.setString(4, email);
            statement.setString(5, phone);
            
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
            if(connect!=null){
                try {
                    connect.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }                                       
        
    private void resetBttActionPerformed(java.awt.event.ActionEvent evt) {                                         
        fullnameText.setText("");
        ageText.setText("");
        emailText.setText("");
        phoneText.setText("");
        genderText.setSelectedIndex(0);
    }                                        

    private void emailTextActionPerformed(java.awt.event.ActionEvent evt) {                                          
    }                                         

    private void deleteBttActionPerformed(java.awt.event.ActionEvent evt) {                                          
        
        String fullname = fullnameText.getText();
        String age = ageText.getText();
        String email = emailText.getText();
        String phone = phoneText.getText();
        String gender = genderText.getSelectedItem().toString();
        if(fullname.isEmpty()||age.isEmpty()||email.isEmpty()||phone.isEmpty()){
            JOptionPane.showMessageDialog(rootPane, "Please insert all field!");
            return;
        }
        Connection connect =null;
        PreparedStatement statement = null;
        try {
            connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/bt?serverTimezone=UTC","root","");
            String query = "delete from teacher where fullname = ? and gender = ? and age = ? and email = ? and phone = ?";
            statement = connect.prepareCall(query);
            statement.setString(1, fullname);
            statement.setString(2, gender);
            statement.setString(3, age);
            statement.setString(4, email);
            statement.setString(5, phone);
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
            if(connect!=null){
                try {
                    connect.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        addDatabase();
    }                                         

    private void findBttActionPerformed(java.awt.event.ActionEvent evt) {                                        
        int flag = 0;
        String fullname = fullnameText.getText();
        String age = ageText.getText();
        String email = emailText.getText();
        String phone = phoneText.getText();
        String gender = genderText.getSelectedItem().toString();
        String search = JOptionPane.showInputDialog("Insert teacher name that you want to find?");
        for (int row = 0; row < tblModel.getRowCount();row++) {
            if (tblModel.getValueAt(row, 1).toString().equalsIgnoreCase(search)) {
                fullnameText.setText(tblModel.getValueAt(row, 1).toString());
                int gend = (tblModel.getValueAt(row, 2).toString().equals("Nam")) ? 0 : 1;
                genderText.setSelectedIndex(gend);
                ageText.setText(tblModel.getValueAt(row, 3).toString());
                emailText.setText(tblModel.getValueAt(row, 4).toString());
                phoneText.setText(tblModel.getValueAt(row, 5).toString());
                flag = 1;
                break;
            }
        }
        if(flag==0) JOptionPane.showMessageDialog(rootPane, "Not Found.");
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
//        addDatabase();
        /* 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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.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 Main().setVisible(true);
                addDatabase();
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextField ageText;
    private javax.swing.JButton deleteBtt;
    private javax.swing.JTextField emailText;
    private javax.swing.JButton findBtt;
    private javax.swing.JTextField fullnameText;
    private javax.swing.JComboBox<String> genderText;
    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.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField phoneText;
    private javax.swing.JButton resetBtt;
    private javax.swing.JButton saveBtt;
    private javax.swing.JTable tableSQL;
    // End of variables declaration                   
}


Nguyễn Hoàng Anh [C1907L]

Ngày viết: 18:33 28/05/2020



/*
 * 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 javaadvanced_quanlysinhvien;

/**
 *
 * @author Redmibook 14
 */
public class Student {
    int no;
    String FullName,Gender,Age,Email,PhoneNumber;

    public Student( String FullName, String Gender, String Age, String Email, String PhoneNumber) {
       
        this.FullName = FullName;
        this.Gender = Gender;
        this.Age = Age;
        this.Email = Email;
        this.PhoneNumber = PhoneNumber;
    }

    public Student() {
    }

    public int getNo() {
        return no;
    }

    public String getFullName() {
        return FullName;
    }

    public String getGender() {
        return Gender;
    }

    public String getAge() {
        return Age;
    }

    public String getEmail() {
        return Email;
    }

    public String getPhoneNumber() {
        return PhoneNumber;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public void setFullName(String FullName) {
        this.FullName = FullName;
    }

    public void setGender(String Gender) {
        this.Gender = Gender;
    }

    public void setAge(String Age) {
        this.Age = Age;
    }

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

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



/*
 * 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 javaadvanced_quanlysinhvien;

import java.awt.List;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Redmibook 14
 */
public class StudentCRUD {

    public void insert(Student std) {
        Connection conn = null;
        PreparedStatement statement = null;

        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentmanager?serverTimezone=UTC", "root", "");
            String query = "insert into student (FullName,Gender,Age,Email,PhoneNumber) values (?,?,?,?,?) ";
            statement = conn.prepareCall(query);

            statement.setString(1, std.getFullName());
            statement.setString(2, std.getGender());
            statement.setString(3, std.getAge());
            statement.setString(4, std.getEmail());
            statement.setString(5, std.getPhoneNumber());
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public ArrayList listStudent() {
        ArrayList<Student> studentList = new ArrayList();
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentmanager?serverTimezone=UTC", "root", "");
            String query = "select * from student";
            statement = conn.prepareCall(query);
            ResultSet result = statement.executeQuery();
            while (result.next()) {
                Student std = new Student(result.getString("FullName"),
                        result.getString("Gender"), result.getString("Age"),
                        result.getString("Email"), result.getString("PhoneNumber"));
                std.setNo(Integer.parseInt(result.getString("no")));
                studentList.add(std);
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return studentList;
    }

    public void delete(int primaryKey) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentmanager?serverTimezone=UTC", "root", "");
            String query = "delete from student where no = ?";
            statement = conn.prepareCall(query);
            statement.setString(1, String.valueOf(primaryKey));
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public ArrayList<Student> search(String name, String phone) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ArrayList<Student> listStudent = new ArrayList();
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentmanager?serverTimezone=UTC", "root", "");
            String query = "select * from student where ('' like ? or FullName like ?) and (0 = ? or PhoneNumber = ?)";
            stmt = conn.prepareCall(query);
            stmt.setString(1, '%' + name + '%');
            stmt.setString(2, '%' + name + '%');
            stmt.setString(3, phone);
            stmt.setString(4, phone);

            ResultSet result = stmt.executeQuery();
            while (result.next()) {
                Student std = new Student(result.getString("FullName"),
                        result.getString("Gender"), result.getString("Age"),
                        result.getString("Email"), result.getString("PhoneNumber"));
                std.setNo(Integer.parseInt(result.getString("no")));
                listStudent.add(std);
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(StudentCRUD.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return listStudent;
    }
}



/*
 * 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 javaadvanced_quanlysinhvien;

import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Redmibook 14
 */
public class StudentsFrame extends javax.swing.JFrame {

    DefaultTableModel tableModel;

    /**
     * Creates new form StudentsFrame
     */
    public StudentsFrame() {
        initComponents();
        tableModel = (DefaultTableModel) tblStudent.getModel();
        tableShow();
    }

    /**
     * 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() {

        searchStudent = new javax.swing.JDialog();
        searchName = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        searchPhone = new javax.swing.JTextField();
        searchBtn = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jlabel = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        FullName = new javax.swing.JTextField();
        Age = new javax.swing.JTextField();
        Email = new javax.swing.JTextField();
        PhoneNumber = new javax.swing.JTextField();
        Gender = new javax.swing.JComboBox<>();
        Save = new javax.swing.JButton();
        Reset = new javax.swing.JButton();
        Delete = new javax.swing.JButton();
        Find = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblStudent = new javax.swing.JTable();

        searchStudent.setTitle("Input Student Name");
        searchStudent.setAlwaysOnTop(true);
        searchStudent.setMinimumSize(new java.awt.Dimension(516, 190));

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

        jLabel1.setText("Name");

        jLabel6.setText("Phone");

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

        javax.swing.GroupLayout searchStudentLayout = new javax.swing.GroupLayout(searchStudent.getContentPane());
        searchStudent.getContentPane().setLayout(searchStudentLayout);
        searchStudentLayout.setHorizontalGroup(
            searchStudentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchStudentLayout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(searchStudentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel6))
                .addGap(75, 75, 75)
                .addGroup(searchStudentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(searchName, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                    .addComponent(searchPhone))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
                .addComponent(searchBtn)
                .addContainerGap())
        );
        searchStudentLayout.setVerticalGroup(
            searchStudentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchStudentLayout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(searchStudentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(searchStudentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(searchPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchBtn))
                .addContainerGap(33, Short.MAX_VALUE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Student Manager");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Input students infomation"));

        jlabel.setText("Full Name :");

        jLabel2.setText("Gender :");

        jLabel3.setText("Age :");

        jLabel4.setText("Email :");

        jLabel5.setText("Phone Number :");

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

        Gender.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Male", "Female" }));

        Save.setText("Save");
        Save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveActionPerformed(evt);
            }
        });

        Reset.setText("Reset");
        Reset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetActionPerformed(evt);
            }
        });

        Delete.setText("Delete");
        Delete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeleteActionPerformed(evt);
            }
        });

        Find.setText("Find");
        Find.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FindActionPerformed(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(56, 56, 56)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlabel, javax.swing.GroupLayout.Alignment.LEADING))
                .addGap(67, 67, 67)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(FullName)
                    .addComponent(Gender, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Age)
                    .addComponent(Email)
                    .addComponent(PhoneNumber)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(Save, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(41, 41, 41)
                        .addComponent(Reset, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(45, 45, 45)
                        .addComponent(Delete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
                        .addComponent(Find, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(88, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(FullName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlabel))
                .addGap(35, 35, 35)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(Gender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(36, 36, 36)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(Age, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(40, 40, 40)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(Email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(PhoneNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Save)
                    .addComponent(Reset)
                    .addComponent(Delete)
                    .addComponent(Find))
                .addGap(37, 37, 37))
        );

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

            },
            new String [] {
                "No", "Full Name", "Gender", "Age", "Email", "Phone Number"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblStudent.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblStudentMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tblStudent);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, 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)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void FullNameActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        
    int no;
    private void DeleteActionPerformed(java.awt.event.ActionEvent evt) {                                       
        StudentCRUD stdCRUD = new StudentCRUD();
        stdCRUD.delete(no);
        tableModel.setRowCount(0);
        tableShow();
    }                                      

    private void tblStudentMouseClicked(java.awt.event.MouseEvent evt) {                                        
        int delRow = tblStudent.getSelectedRow();
        no = Integer.parseInt(tblStudent.getModel().getValueAt(delRow, 0).toString());
        System.out.println(no);
    }                                       

    private void SaveActionPerformed(java.awt.event.ActionEvent evt) {                                     
        Student std = new Student(FullName.getText(), (String) Gender.getSelectedItem(), Age.getText(), Email.getText(), PhoneNumber.getText());
        StudentCRUD stdCRUD = new StudentCRUD();
        stdCRUD.insert(std);
        tableModel.setRowCount(0);
        tableShow();
    }                                    

    private void ResetActionPerformed(java.awt.event.ActionEvent evt) {                                      
        FullName.setText("");
        Gender.setSelectedItem("Male");
        Age.setText("");
        Email.setText("");
        PhoneNumber.setText("");
    }                                     

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

    private void FindActionPerformed(java.awt.event.ActionEvent evt) {                                     
        searchStudent.show();
    }                                    

    private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
        StudentCRUD stdCRUD = new StudentCRUD();
        ArrayList<Student> students = stdCRUD.search(searchName.getText(), searchPhone.getText());
        tableModel.setRowCount(0);
        for (int i = 0; i < students.size(); i++) {
            tableModel.addRow(new Object[]{students.get(i).no, students.get(i).getFullName(),
                students.get(i).getGender(), students.get(i).getAge(),
                students.get(i).getEmail(), students.get(i).getPhoneNumber()});
        }

    }                                         
    private void tableShow() {
        StudentCRUD stdCRUD = new StudentCRUD();
        ArrayList<Student> students = stdCRUD.listStudent();
        for (int i = 0; i < students.size(); i++) {
            tableModel.addRow(new Object[]{students.get(i).no, students.get(i).getFullName(),
                students.get(i).getGender(), students.get(i).getAge(),
                students.get(i).getEmail(), students.get(i).getPhoneNumber()});
        }

    }

    /**
     * @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(StudentsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(StudentsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(StudentsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(StudentsFrame.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 StudentsFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextField Age;
    private javax.swing.JButton Delete;
    private javax.swing.JTextField Email;
    private javax.swing.JButton Find;
    private javax.swing.JTextField FullName;
    private javax.swing.JComboBox<String> Gender;
    private javax.swing.JTextField PhoneNumber;
    private javax.swing.JButton Reset;
    private javax.swing.JButton Save;
    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 jScrollPane2;
    private javax.swing.JLabel jlabel;
    private javax.swing.JButton searchBtn;
    private javax.swing.JTextField searchName;
    private javax.swing.JTextField searchPhone;
    private javax.swing.JDialog searchStudent;
    private javax.swing.JTable tblStudent;
    // End of variables declaration                   
}


Phí Văn Long [T1907A]

Ngày viết: 14:00 07/04/2020



/*
 * 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 QLSV.JavaSwing;

/**
 *
 * @author Admin
 */
public class Student {
    int id;
    String fullname,gender,email,phoneNumber;
    int age;

    public Student() {
    }

    public Student(int id, String fullname, String gender, String email, String phoneNumber, int age) {
        this.id = id;
        this.fullname = fullname;
        this.gender = gender;
        this.email = email;
        this.phoneNumber = phoneNumber;
        this.age = age;
    }

    public Student(String fullname, String gender, String email, String phoneNumber, int age) {
        this.fullname = fullname;
        this.gender = gender;
        this.email = email;
        this.phoneNumber = phoneNumber;
        this.age = age;
    }
    
    
    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 getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
    
}



/*
 * 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 QLSV.JavaSwing;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * CRUD(insert,update,delete,findAll)
 *
 * @author Admin
 */
public class StudentModify {

    public static List<Student> finAll() {
        List<Student> studentList = new ArrayList<>();
        Connection conn = null;
        Statement stm = null;
        try {
            //lay tat ca dssv
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t1907a?serverTimezone=UTC", "root", "");
            //query
            String sql = "select * from students";
            stm = conn.createStatement();

            ResultSet resultSet = stm.executeQuery(sql);

            while (resultSet.next()) {
                Student std = new Student(resultSet.getInt("id"), resultSet.getString("fullname"), resultSet.getString("gender"), resultSet.getString("email"), resultSet.getString("phoneNumber"), resultSet.getInt("age"));
                studentList.add(std);
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (stm != null) {
                try {
                    stm.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        //ketthuc
        return studentList;
    }

    public static void insert(Student std) {
        Connection conn = null;
        PreparedStatement stm = null;
        try {
            //lay tat ca dssv
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t1907a?serverTimezone=UTC", "root", "");
            //query
            String sql = "insert into students(fullname,gender,age,email,phonenumber) values (?,?,?,?,?)";
            stm = conn.prepareCall(sql);
            stm.setString(1, std.getFullname());
            stm.setString(2, std.getGender());
            stm.setInt(3, std.getAge());
            stm.setString(4, std.getEmail());
            stm.setString(5, std.getPhoneNumber());

            stm.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (stm != null) {
                try {
                    stm.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        //ketthuc
    }

    public static void update(Student std) {
        Connection conn = null;
        PreparedStatement stm = null;
        try {
            //lay tat ca dssv
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t1907a?serverTimezone=UTC", "root", "");
            //query
            String sql = "update students set fullname=?,gender=?,age=?,email=?,phonenumber=? where id = ?";
            stm = conn.prepareCall(sql);
            
            stm.setString(1, std.getFullname());
            stm.setString(2, std.getGender());
            stm.setInt(3, std.getAge());
            stm.setString(4, std.getEmail());
            stm.setString(5, std.getPhoneNumber());
            stm.setInt(6, std.getId());

            stm.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (stm != null) {
                try {
                    stm.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        //ketthuc
    }

    public static void delete(int id) {
        Connection conn = null;
        PreparedStatement stm = null;
        try {
            //lay tat ca dssv
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t1907a?serverTimezone=UTC", "root", "");
            //query
            String sql = "delete from students  where id = ?";
            stm = conn.prepareCall(sql);

            stm.setInt(1, id);

            stm.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (stm != null) {
                try {
                    stm.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        //ketthuc
    }
    
    public static List<Student> findByFullName(String fullname) {
        List<Student> studentList = new ArrayList<>();
        Connection conn = null;
        PreparedStatement stm = null;
        try {
            //lay tat ca dssv
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t1907a?serverTimezone=UTC", "root", "");
            //query
            String sql = "select * from students  where fullname like ?";
            stm = conn.prepareCall(sql);

            stm.setString(1,"%" + fullname + "%");
            ResultSet resultSet = stm.executeQuery();
            
             while (resultSet.next()) {
                Student std = new Student(resultSet.getInt("id"), resultSet.getString("fullname"), resultSet.getString("gender"), resultSet.getString("email"), resultSet.getString("phoneNumber"), resultSet.getInt("age"));
                studentList.add(std);
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (stm != null) {
                try {
                    stm.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        //ketthuc
        return studentList;
    }
}



/*
 * 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 QLSV.JavaSwing;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Admin
 */
public class QLSV extends javax.swing.JFrame {
    DefaultTableModel tableModel;
    
    List <Student>  studentList = new ArrayList<>();
    /**
     * Creates new form QLSV
     */
   
    public QLSV() {
        initComponents();
        tableModel = (DefaultTableModel) tblStudent.getModel();
        showStudent();
        
      
    }
    private void showStudent(){
     studentList = StudentModify.finAll();
    
    tableModel.setRowCount(0);
    
    studentList.forEach((student) -> {
        tableModel.addRow(new Object[]{tableModel.getRowCount() + 1,student.getFullname(),student.getGender(),student.getEmail(),student.getPhoneNumber()});
        });
}
    /**
     * 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() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtFullName = new javax.swing.JTextField();
        txtAge = new javax.swing.JTextField();
        txtEmail = new javax.swing.JTextField();
        txtPhoneNumber = new javax.swing.JTextField();
        cbGender = new javax.swing.JComboBox<>();
        btnSave = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnFind = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblStudent = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Input Student"));

        jLabel1.setText("Full Name :");

        jLabel2.setText("Age :");

        jLabel3.setText("Gender :");

        jLabel4.setText("Email :");

        jLabel5.setText("PhoneNumber :");

        cbGender.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Male", "Female" }));

        btnSave.setBackground(new java.awt.Color(255, 255, 255));
        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnReset.setBackground(new java.awt.Color(255, 153, 0));
        btnReset.setText("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnFind.setText("Find");
        btnFind.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFindActionPerformed(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(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(txtEmail, javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(txtFullName, javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(txtPhoneNumber, javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(txtAge, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(47, 47, 47)
                                    .addComponent(btnReset)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(btnDelete)
                                    .addGap(37, 37, 37)
                                    .addComponent(btnFind, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(25, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(txtFullName)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(cbGender)
                        .addGap(10, 10, 10)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtAge, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtPhoneNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(61, 61, 61)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnReset)
                    .addComponent(btnDelete)
                    .addComponent(btnFind))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

            },
            new String [] {
                "ID", "Full Name", "Gender", "Age", "Email", "Phone Number"
            }
        ));
        jScrollPane1.setViewportView(tblStudent);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addContainerGap(23, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(21, Short.MAX_VALUE))
        );

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

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        txtFullName.setText("");
        cbGender.setSelectedIndex(0);
        txtAge.setText("");
        txtEmail.setText("");
        txtPhoneNumber.setText("");
        
    }                                        

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        String fullname = txtFullName.getText();
        String gender = cbGender.getSelectedItem().toString();
        int age = Integer.parseInt(txtAge.getText());
        String email = txtEmail.getText();
        String phoneNumber = txtPhoneNumber.getText();
        
        Student std = new Student(fullname,gender,email,phoneNumber,age);
        
        StudentModify.insert(std);
        
        showStudent();
    }                                       

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        int selectedIndex = tblStudent.getSelectedRow();
        if (selectedIndex >= 0) {
            Student std = studentList.get(selectedIndex);
            
            //show ra log de lua chon
            int option = JOptionPane.showConfirmDialog(this, "Do you want to delete this item?");
            System.out.println("option" + option);
            
            if (option == 0 ) {
                StudentModify.delete(std.getId());
                
                showStudent();
            }
        }
    }                                         

    private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        String input = JOptionPane.showInputDialog(this,"Enter full name to search");   
        
        
        if (input.length() > 0 && input != null  ) {  
            studentList =  StudentModify.findByFullName(input);
            tableModel.setRowCount(0);
            
            studentList.forEach((student) -> {
            tableModel.addRow(new Object[]{tableModel.getRowCount() + 1,student.getFullname(),student.getGender(),student.getEmail(),student.getPhoneNumber()});                     
        });
        }else{
            showStudent();
        }
    }                                       

    /**
     * @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(QLSV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(QLSV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(QLSV.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(QLSV.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 QLSV().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnFind;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSave;
    private javax.swing.JComboBox<String> cbGender;
    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.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblStudent;
    private javax.swing.JTextField txtAge;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtFullName;
    private javax.swing.JTextField txtPhoneNumber;
    // End of variables declaration                   
}


Tài Liệu Tham Khảo

Ứng Dụng Tiện Ích



Đã sao chép!!!