By GokiSoft.com| 22:44 29/10/2021|
Java Advanced

[Video] Quản lý sinh viên + XML + JSON + MySQL bằng Java

Hướng dẫn chữa bài tập

 Quản lý sinh viên + XML + JSON + MySQL bằng Java


B1. Tao project => DONE
B2. Tao Form => DONE
B3. Download library jdbc mysql driver => add project
(keyword: jdbc mysql driver maven)
B4. Mapping tables trong Database => class object
B5. Class Object => insert, update, find, findAll, delete



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

/**
 *
 * @author Diep.Tran
 */
public class Students {
    String rollno, fullname, gender, email, address;

    public Students() {
    }

    public Students(String rollno, String fullname, String gender, String email, String address) {
        this.rollno = rollno;
        this.fullname = fullname;
        this.gender = gender;
        this.email = email;
        this.address = address;
    }

    public String getRollno() {
        return rollno;
    }

    public void setRollno(String rollno) {
        this.rollno = rollno;
    }

    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 getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "Students{" + "rollno=" + rollno + ", fullname=" + fullname + ", gender=" + gender + ", email=" + email + ", address=" + address + '}';
    }
    
    public void display() {
        System.out.println(this);
    }
    
    public String getXMLString() {
        return "<student>\n" +
"		<rollno>"+rollno+"</rollno>\n" +
"		<fullname>"+fullname+"</fullname>\n" +
"		<email>"+email+"</email>\n" +
"		<gender>"+gender+"</gender>\n" +
"		<address>"+address+"</address>\n" +
"	</student>";
    }
}



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

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 Diep.Tran
 */
public class StudentsModify {
    public static List<Students> findAll() {
        Connection conn = null;
        Statement statement = null;
        List<Students> studentList = new ArrayList<>();
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            //query
            statement = conn.createStatement();
            String sql = "select * from students";
            
            ResultSet resultSet = statement.executeQuery(sql);
            
            while(resultSet.next()) {
                Students std = new Students(resultSet.getString("rollno"), 
                        resultSet.getString("fullname"), 
                        resultSet.getString("gender"), 
                        resultSet.getString("email"), 
                        resultSet.getString("address"));
                studentList.add(std);
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        return studentList;
    }
    
    public static List<Students> findByRollnoOrFullname(String searchValue) {
        Connection conn = null;
        Statement statement = null;
        List<Students> studentList = new ArrayList<>();
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            //query
            String sql = "select * from students where rollno like '%"+searchValue+"%' or fullname like '%"+searchValue+"%'";
            statement = conn.createStatement();
            
            ResultSet resultSet = statement.executeQuery(sql);
            
            while(resultSet.next()) {
                Students std = new Students(resultSet.getString("rollno"), 
                        resultSet.getString("fullname"), 
                        resultSet.getString("gender"), 
                        resultSet.getString("email"), 
                        resultSet.getString("address"));
                studentList.add(std);
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        return studentList;
    }
    
    private static void insert(Students std) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            String sql = "insert into students(rollno, fullname, gender, email, address)"
                    + "values (?, ?, ?, ?, ?)";
            statement = conn.prepareStatement(sql);
            statement.setString(1, std.getRollno());
            statement.setString(2, std.getFullname());
            statement.setString(3, std.getGender());
            statement.setString(4, std.getEmail());
            statement.setString(5, std.getAddress());
            
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    private static void update(Students std) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            String sql = "update students set fullname = ?, gender = ?, email = ?, address = ?"
                    + " where rollno = ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, std.getFullname());
            statement.setString(2, std.getGender());
            statement.setString(3, std.getEmail());
            statement.setString(4, std.getAddress());
            statement.setString(5, std.getRollno());
            
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
    public static void save(Students std) {
        Students stdFind = find(std.getRollno());
        
        if(stdFind == null) {
            insert(std);
        } else {
            update(std);
        }
    }
    
    public static Students find(String rollno) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            //query
            String sql = "select * from students where rollno = ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, rollno);
            
            ResultSet resultSet = statement.executeQuery();
            
            while(resultSet.next()) {
                Students std = new Students(resultSet.getString("rollno"), 
                        resultSet.getString("fullname"), 
                        resultSet.getString("gender"), 
                        resultSet.getString("email"), 
                        resultSet.getString("address"));
                return std;
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return null;
    }
    
    public static void delete(String rollno) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            //Open connection to Database
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/quanlysinhvien", "root", "");
            
            //query
            String sql = "delete from students where rollno = ?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, rollno);
            
            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(StudentsModify.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}



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

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.json.JSONArray;

/**
 *
 * @author Diep.Tran
 */
public class MainFrame extends javax.swing.JFrame {

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
    }

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

        jButton4 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtRollNo = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtFullname = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtEmail = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtAddress = new javax.swing.JTextField();
        cbGender = new javax.swing.JComboBox<>();
        btnSearch = new javax.swing.JButton();
        btnImportXML = new javax.swing.JButton();
        btnImportJSON = new javax.swing.JButton();
        btnExportXML = new javax.swing.JButton();
        btnExportJSON = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();

        jButton4.setText("Search");

        jButton6.setText("Search");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Roll No:");

        jLabel2.setText("Full Name: ");

        jLabel3.setText("Email:");

        jLabel4.setText("Gender:");

        jLabel5.setText("Address:");

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

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

        btnImportXML.setText("Import XML");
        btnImportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportXMLActionPerformed(evt);
            }
        });

        btnImportJSON.setText("Import JSON");
        btnImportJSON.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportJSONActionPerformed(evt);
            }
        });

        btnExportXML.setText("Export XML");
        btnExportXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportXMLActionPerformed(evt);
            }
        });

        btnExportJSON.setText("Export JSON");
        btnExportJSON.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExportJSONActionPerformed(evt);
            }
        });

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

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

        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(42, 42, 42)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtRollNo, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtFullname, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnSave)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnReset))
                            .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnImportXML, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))
                        .addContainerGap())
                    .addComponent(btnImportJSON, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)
                    .addComponent(btnExportXML, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)
                    .addComponent(btnExportJSON, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtRollNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSearch))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtFullname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnImportXML))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnImportJSON))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnExportXML))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnExportJSON))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnReset))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        String rollno = txtRollNo.getText();
        String fullname = txtFullname.getText();
        String gender = cbGender.getSelectedItem().toString();
        String address = txtAddress.getText();
        String email = txtEmail.getText();
        
        if(rollno.isEmpty() || fullname.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "No empty rollno or fullname");
            return;
        }
        
        Students std = new Students(rollno, fullname, gender, email, address);
        
        StudentsModify.save(std);
        
        btnResetActionPerformed(null);
        
        JOptionPane.showMessageDialog(rootPane, "Save success!!!");
    }                                       

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

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        String rollno = txtRollNo.getText();
        if(rollno.isEmpty()) {
            JOptionPane.showMessageDialog(rootPane, "No empty rollno");
            return;
        }
        Students std = StudentsModify.find(rollno);
        if(std == null) {
            JOptionPane.showMessageDialog(rootPane, "Not found any student by rollno");
            return;
        }
        txtFullname.setText(std.getFullname());
        txtEmail.setText(std.getEmail());
        txtAddress.setText(std.getAddress());
        cbGender.setSelectedItem(std.getGender());
    }                                         

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

    private void btnImportJSONActionPerformed(java.awt.event.ActionEvent evt) {                                              
        FileReader reader = null;
        try {
            // TODO add your handling code here:
            File file = null;
            JFileChooser fileChooser = new JFileChooser();
            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                file = fileChooser.getSelectedFile();
                // load from file
            }   if(file == null) {
                JOptionPane.showMessageDialog(rootPane, "Not file selected");
                return;
            }
            java.lang.reflect.Type classOfT = new TypeToken<ArrayList<Students>>(){}.getType();
            reader = new FileReader(file);
            Gson gson = new Gson();
            ArrayList<Students> list = gson.fromJson(reader, classOfT);
            
            for (Students std : list) {
                StudentsModify.save(std);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        JOptionPane.showMessageDialog(rootPane, "Import JSON success!!!");
    }                                             

    private void btnExportXMLActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
        File file = null;
        
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
          file = fileChooser.getSelectedFile();
          // save to file
        }
        if(file == null) {
            JOptionPane.showMessageDialog(rootPane, "Not save");
            return;
        }
        
        List<Students> studentList = searchStudents();
        
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);

            String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                    "<students>";
            fos.write(str.getBytes());
            
            for (Students std : studentList) {
                fos.write(std.getXMLString().getBytes());
            }
            
            str = "</students>";
            fos.write(str.getBytes());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Export XML success!!!");
    }                                            

    private void btnExportJSONActionPerformed(java.awt.event.ActionEvent evt) {                                              
        File file = null;
        
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
          file = fileChooser.getSelectedFile();
          // save to file
        }
        if(file == null) {
            JOptionPane.showMessageDialog(rootPane, "Not save");
            return;
        }
        
        FileOutputStream fos = null;
        try {
            // TODO add your handling code here:
            List<Students> studentList = searchStudents();
            //convert List to JSON file
            JSONArray arr = new JSONArray(studentList);
//            System.out.println(arr.toString());

            fos = new FileOutputStream(file);
            byte[] b = arr.toString().getBytes();
            
            fos.write(b);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        JOptionPane.showMessageDialog(rootPane, "Export JSON success!!!");
    }                                             

    private List<Students> searchStudents() {
        String searchValue = JOptionPane.showInputDialog("Enter search value");
        
        List<Students> studentList = null;
        
        if(searchValue.isEmpty()) {
            studentList = StudentsModify.findAll();
        } else {
            studentList = StudentsModify.findByRollnoOrFullname(searchValue);
        }
        return studentList;
    }
    
    /**
     * @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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.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 MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnExportJSON;
    private javax.swing.JButton btnExportXML;
    private javax.swing.JButton btnImportJSON;
    private javax.swing.JButton btnImportXML;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSearch;
    private javax.swing.JComboBox<String> cbGender;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton6;
    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.JTextField txtAddress;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtFullname;
    private javax.swing.JTextField txtRollNo;
    // End of variables declaration                   
}


Tham khảo source code tại lớp học khác

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

5

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