• Decoded World

    The Mysteries of Humanity: Leonardo da Vinci

  • Decoded World

    The Unsung Hero: Nikola Tesla

  • Decoded World

    The Wizard of Light: Thomas Edison

  • Decoded World

    Adolf Hitler: The Master Manipulator

Showing posts with label ADD2. Show all posts
Showing posts with label ADD2. Show all posts

08 May 2016

ADD2 Test Eclipse - Aptech FPT 2016 - Validating and Encrypting Password Saving database Java Swing

 TEST ADD2  - Aptech FPT 2016




1 - Create database.

CREATE DATABASE contactinfo;

CREATE TABLE `contact` (
  `email` varchar(50) NOT NULL,
  `pass` varchar(30) NOT NULL,
  `phone` varchar(20) 
) ;

2 - DBConnection.java


Add library connect database
package controller;

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

public class DBConnection {

 private static Connection conn;
 static final String DRIVER_JDBC = "com.mysql.jdbc.Driver";
 static final String DB_URL = "jdbc:mysql://localhost/contactinfo";
 static final String USER = "root";
 static final String PASS = "1234567";

 public static Connection getConnection() {
  try {
   Class.forName(DRIVER_JDBC);
   conn = DriverManager.getConnection(DB_URL, USER, PASS);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return conn;
 }
}





3 - View.java




Button send >> Validating



Button reset >> Reset


package view;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;

import model.Contact;
import model.ContactDAO;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPasswordField;

public class Vew {

 private JFrame frmDesignPreviewexam;
 private JTextField txtEmail;
 private JTextField txtPhone;
 private JPasswordField txtPass;
 private JPasswordField txtCpass;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     Vew window = new Vew();
     window.frmDesignPreviewexam.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the application.
  */
 public Vew() {
  initialize();
 }

 /**
  * Initialize the contents of the frame.
  */
 private void initialize() {
  frmDesignPreviewexam = new JFrame();
  frmDesignPreviewexam.setTitle("Design Preview [Exam04]");
  frmDesignPreviewexam.setBounds(100, 100, 450, 278);
  frmDesignPreviewexam.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frmDesignPreviewexam.getContentPane().setLayout(null);
  
  txtEmail = new JTextField();
  txtEmail.setBounds(197, 38, 167, 20);
  frmDesignPreviewexam.getContentPane().add(txtEmail);
  txtEmail.setColumns(10);
  
  txtPhone = new JTextField();
  txtPhone.setColumns(10);
  txtPhone.setBounds(197, 131, 167, 20);
  frmDesignPreviewexam.getContentPane().add(txtPhone);
  
  JButton btnSend = new JButton("Send");
  btnSend.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    //Validating email, pass, is phone not null
    if(txtEmail.getText().isEmpty()){
     JOptionPane.showMessageDialog(null, "Email not null \n Enter email !");
    }else if(txtPass.getText().isEmpty()){
     JOptionPane.showMessageDialog(null, "Password not null \n Enter Password ! ");
    }else if(txtCpass.getText().isEmpty()){
     JOptionPane.showMessageDialog(null, "Confirm password not null \n Enter Confirm password ");
    }else if(txtPhone.getText().isEmpty()){
     JOptionPane.showMessageDialog(null, "Phone number not null \n Enter Phone number");
    }else if(txtPass.getText() != txtCpass.getText()){
     //Action do some thing setter to contact
     Contact contact = new Contact();
     if(txtPass.getText().equals(txtCpass.getText())){
      contact.setEmail(txtEmail.getText());
      contact.setPhone(txtPhone.getText());
      contact.setPass(txtPass.getText());
      JOptionPane.showMessageDialog(null, "Send to database successfully!");
      
      ContactDAO contactDao = new ContactDAO();
      contactDao.addContact(contact);
     }else{
      JOptionPane.showMessageDialog(null, "Confirm password Wrong!");
     }
    }
   }
  });
  btnSend.setBounds(152, 185, 89, 23);
  frmDesignPreviewexam.getContentPane().add(btnSend);
  
  JButton btnReset = new JButton("Reset");
  btnReset.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    txtEmail.setText("");
    txtPass.setText("");
    txtCpass.setText("");
    txtPhone.setText("");
   }
  });
  btnReset.setBounds(275, 185, 89, 23);
  frmDesignPreviewexam.getContentPane().add(btnReset);
  
  JLabel lblPassword = new JLabel("Password");
  lblPassword.setBounds(44, 72, 111, 14);
  frmDesignPreviewexam.getContentPane().add(lblPassword);
  
  JLabel lblEmail = new JLabel("Email");
  lblEmail.setBounds(44, 41, 111, 14);
  frmDesignPreviewexam.getContentPane().add(lblEmail);
  
  JLabel lblConfirmPassword = new JLabel("Confirm Password");
  lblConfirmPassword.setBounds(44, 103, 111, 14);
  frmDesignPreviewexam.getContentPane().add(lblConfirmPassword);
  
  JLabel lblPhoneNumber = new JLabel("Phone Number");
  lblPhoneNumber.setBounds(44, 134, 111, 14);
  frmDesignPreviewexam.getContentPane().add(lblPhoneNumber);
  
  txtPass = new JPasswordField();
  txtPass.setBounds(197, 69, 167, 20);
  frmDesignPreviewexam.getContentPane().add(txtPass);
  
  txtCpass = new JPasswordField();
  txtCpass.setBounds(197, 100, 167, 20);
  frmDesignPreviewexam.getContentPane().add(txtCpass);
 }
}

4 - Contact.java  

>> Set and Get  Constructor
package model;

public class Contact {

 private String email;
 private String pass;
 private String phone;

 public String getEmail() {
  return email;
 }

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

 public String getPass() {
  return pass;
 }

 public void setPass(String pass) {
  this.pass = pass;
 }

 public String getPhone() {
  return phone;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

 public Contact() {
  super();
  // TODO Auto-generated constructor stub
 }

}

5 - ContactDAO.java  

>> Encrypt MD5  & Insert




package model;

import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import controller.DBConnection;

public class ContactDAO {
 
 private Connection conn;
 private PreparedStatement stmt;
 
 public ContactDAO() {
  conn = DBConnection.getConnection();
 }
 
 private static String key = "1234abcd";

 private static String encrypt(String message) throws Exception {

  Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
  DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
  SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
  IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
  cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
  return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
 }

 private static String toHexString(byte b[]) {
  StringBuffer hexString = new StringBuffer();
  for (int i = 0; i < b.length; i++) {
   String plainText = Integer.toHexString(0xff & b[i]);
   if (plainText.length() < 2)
    plainText = "0" + plainText;
   hexString.append(plainText);
  }
  return hexString.toString();
 }
 
 public void addContact(Contact contact){
  String sql ="Insert Into contact Values(?,?,?)";
  try {
   stmt = conn.prepareStatement(sql);
   stmt.setString(1, contact.getEmail());
   stmt.setString(2, encrypt(contact.getPass()));
   stmt.setString(3, contact.getPhone());
   
   stmt.executeUpdate();
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 
 
}


Làm theo cách 2


Database Connection
Java 2016
package md5Encrypt;

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

public class DBUtil {
 private static Connection conn;
 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
 static final String DB_URL = "jdbc:mysql://localhost/testencryptmd5";
 static final String DB_USER = "root";
 static final String DB_PASS = "1234567";

 public static Connection getConnection() {
  if (conn != null) {
   return conn;
  } else {

   try {
    Class.forName(JDBC_DRIVER);
    conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
   } catch (Exception e) {
    e.printStackTrace();
   }

   return conn;
  }
 }

}

Program
Java 2016
package md5Encrypt;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Program {

 private JFrame frame;
 private JTextField txtEmail;
 private JPasswordField txtPass;
 private JPasswordField txtPassConfig;
 private JTextField txtPhone;

 /**
  * Launch the application.
  */
 private PreparedStatement stmt;
 private Connection conn;
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     Program window = new Program();
     window.frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the application.
  */
 public Program() {
  initialize();
  try {
   conn = DBUtil.getConnection();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

  private static String key = "1234abcd";
  private static String encrypt(String message) throws Exception {

    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
    IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
    return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
   }

   private static String toHexString(byte b[]) {
    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < b.length; i++) {
     String plainText = Integer.toHexString(0xff & b[i]);
     if (plainText.length() < 2)
      plainText = "0" + plainText;
     hexString.append(plainText);
    }
    return hexString.toString();
   }
 /**
  * Initialize the contents of the frame.
  */
 private void initialize() {
  frame = new JFrame();
  frame.setBounds(100, 100, 450, 300);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().setLayout(null);
  
  JLabel lblSend = new JLabel("Send  Your Contact");
  lblSend.setFont(new Font("Tahoma", Font.BOLD, 30));
  lblSend.setBounds(53, 11, 371, 34);
  frame.getContentPane().add(lblSend);
  
  txtEmail = new JTextField();
  txtEmail.setBounds(158, 68, 190, 20);
  frame.getContentPane().add(txtEmail);
  txtEmail.setColumns(10);
  
  JLabel lblEmail = new JLabel("Email:");
  lblEmail.setBounds(40, 71, 46, 14);
  frame.getContentPane().add(lblEmail);
  
  txtPass = new JPasswordField();
  txtPass.setBounds(158, 99, 190, 20);
  frame.getContentPane().add(txtPass);
  
  JLabel lblPassword = new JLabel("Password");
  lblPassword.setBounds(40, 102, 65, 14);
  frame.getContentPane().add(lblPassword);
  
  txtPassConfig = new JPasswordField();
  txtPassConfig.setBounds(158, 132, 190, 20);
  frame.getContentPane().add(txtPassConfig);
  
  JLabel lblConfigPassword = new JLabel("Config Password");
  lblConfigPassword.setBounds(40, 135, 108, 14);
  frame.getContentPane().add(lblConfigPassword);
  
  JLabel lblPhoneNumber = new JLabel("Phone number:");
  lblPhoneNumber.setBounds(40, 171, 108, 14);
  frame.getContentPane().add(lblPhoneNumber);
  
  txtPhone = new JTextField();
  txtPhone.setBounds(157, 168, 191, 20);
  frame.getContentPane().add(txtPhone);
  txtPhone.setColumns(10);
  
  JButton btnSend = new JButton("Send ");
  btnSend.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if(txtEmail.getText().equals("")){
     JOptionPane.showMessageDialog(null, "Please enter email!");
    }else if(txtPhone.getText().equals("")){
     JOptionPane.showMessageDialog(null, "Please enter number phone!");
    }else if(txtPass.getText().equals("")){
     JOptionPane.showMessageDialog(null, "Please enter pass!");
    }else if(txtPassConfig.getText().equals("")){
     JOptionPane.showMessageDialog(null, "Please enter pass config!");
    }else if(txtPass.getText().equals(txtPassConfig.getText())!= true){
     JOptionPane.showMessageDialog(null, "Pass Config Wrong!!");
    }else{
     String sql = "INSERT INTO `testencryptmd5`.`manager` ( `email`, `pass`, `phone`) VALUES ( ?, ?, ?)";
     try {
      stmt = conn.prepareStatement(sql);
      stmt.setString(1, txtEmail.getText());
      stmt.setString(2, encrypt(txtPass.getText()));
      stmt.setString(3, txtPhone.getText());
      stmt.executeUpdate();
     } catch (Exception e2) {
      e2.printStackTrace();
     }
      JOptionPane.showMessageDialog(null, "sent successfully!");
    }
   }
  });
  btnSend.setBounds(100, 211, 89, 23);
  frame.getContentPane().add(btnSend);
  
  JButton btnReset = new JButton("Reset");
  btnReset.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    txtEmail.setText(null);
    txtPass.setText(null);
    txtPassConfig.setText(null);
    txtPhone.setText(null);
   }
  });
  btnReset.setBounds(259, 211, 89, 23);
  frame.getContentPane().add(btnReset);
 }
}




06 May 2016

Min Max Avg Sum in java swing Eclipse

Min Max Avg Sum in java swing Eclipse


Call method java eclipse


AVG


Max - Max Collection


Min - Min Collection



Sum


View.java
package view;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import controller.DBUtils;
import model.User;

public class View {

 private JFrame frmPersonTable;
 private JTextField txtID;
 private JTextField txtFname;
 private JTextField txtLname;
 private JTextField txtAge;
 public JTable table;

 private PreparedStatement stmt;
 private ResultSet rs;
 private Connection conn;
 private JTextField txtAvg;
 private JTextField txtMax;
 private JTextField txtMin;
 private JTextField txtSum;
 
 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     View window = new View();
     window.frmPersonTable.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the application.
  */
 public View() {
  initialize();
  try {
   conn = DBUtils.getConnection();
  } catch (Exception e) {
   e.printStackTrace();
  }

  showTable();
  
  getAvg();
  getMax();
  getMin();
  getSum();
 }

 public ArrayList<User> getArrayList(){
  ArrayList <User> list  = new ArrayList();
  try {
   stmt = conn.prepareStatement("Select * From person.user");
   rs = stmt.executeQuery();
   while(rs.next()){
    User user = new User(rs.getInt("id"),rs.getString("firstname"),rs.getString("lastname"),rs.getInt("age"));
    list.add(user);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  return list;
 }
 public void showTable(){
  ArrayList <User> list = getArrayList();
  DefaultTableModel model = (DefaultTableModel)table.getModel();
  Object[] cols = new Object[4];
  for (int i = 0; i < list.size(); i++) {
   cols[0] = list.get(i).getId();
   cols[1] = list.get(i).getFirstName();
   cols[2] = list.get(i).getLastName();
   cols[3] = list.get(i).getAge();
   model.addRow(cols);
  }
 }
 
 public void queryUpdate(String sql,String message){
  try {
   stmt = conn.prepareStatement(sql);
   if(stmt.executeUpdate()==1){
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.setRowCount(0);
    showTable();
    JOptionPane.showMessageDialog(null, message + " Successfully!");
   }
  } catch (SQLException se) {
   se.printStackTrace();
  }
 }
 
 public void getAvg(){
  float sum  =0;
  for (int i = 0; i < table.getRowCount(); i++) {
   sum = sum+Integer.parseInt(table.getValueAt(i, 3).toString());
  }
  float avg = sum/table.getRowCount();
  txtAvg.setText(Float.toString(avg));
 }
 
 public void getMax(){
  int max = 0;
  for (int i = 0; i < table.getRowCount(); i++) {
   int val = Integer.parseInt(table.getValueAt(i, 3).toString());
   if(val>max){
    max=val;
   }
  }
  txtMax.setText(Integer.toString(max));
 }
 //Method 2
  public void getMaxCollect()
     {
         ArrayList<Integer> list = new ArrayList<Integer>();
         for(int i = 0; i < table.getRowCount(); i++)
         {
             list.add(Integer.parseInt(table.getValueAt(i, 3).toString()));
         }
         
         int max = Collections.max(list);
         txtMax.setText(Integer.toString(max));
     }
 
 public void getMin(){
  int min =0;
  for (int i = 0; i < table.getRowCount(); i++) {
    if(i == 0)
             {
                 min = Integer.parseInt(table.getValueAt(i, 3).toString());
             }
             else{
                 int val = Integer.parseInt(table.getValueAt(i, 3).toString());
                 if(min > val)
                 {
                     min = val;
                 }
             }
  }
  txtMin.setText(Integer.toString(min));
 }
 
 // Methode 2
    public void getMinCollect()
    {
        ArrayList<Integer> list = new ArrayList<Integer>();
        
        for(int i = 0; i < table.getRowCount(); i++)
        {
            list.add(Integer.parseInt(table.getValueAt(i, 3).toString()));
        }
        
        int min = Collections.min(list);
        txtMin.setText(Integer.toString(min));
    }
 
 
 public void getSum()
    {
        int sum = 0;
        for(int i = 0; i < table.getRowCount(); i++)
        {
            sum = sum + Integer.parseInt(table.getValueAt(i, 3).toString());
        }
        
        txtSum.setText(Integer.toString(sum));
    }
 /**
  * Initialize the contents of the frame.
  */
 private void initialize() {
  frmPersonTable = new JFrame();
  frmPersonTable.setTitle("Person Table\r\n");
  frmPersonTable.setBounds(100, 100, 460, 433);
  frmPersonTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frmPersonTable.getContentPane().setLayout(null);
  
  txtID = new JTextField();
  txtID.setBounds(137, 13, 127, 20);
  frmPersonTable.getContentPane().add(txtID);
  txtID.setColumns(10);
  
  txtFname = new JTextField();
  txtFname.setColumns(10);
  txtFname.setBounds(137, 44, 127, 20);
  frmPersonTable.getContentPane().add(txtFname);
  
  txtLname = new JTextField();
  txtLname.setColumns(10);
  txtLname.setBounds(137, 80, 127, 20);
  frmPersonTable.getContentPane().add(txtLname);
  
  txtAge = new JTextField();
  txtAge.setColumns(10);
  txtAge.setBounds(137, 114, 127, 20);
  frmPersonTable.getContentPane().add(txtAge);
  
  JButton btnInser = new JButton("Inser");
  btnInser.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\add-icon.png"));
  btnInser.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    String sql ="INSERT INTO person.user (firstname, lastname, age) "
       + "VALUES ('"+txtFname.getText()+"', '"+txtLname.getText()+"', '"+txtAge.getText()+"')";
    queryUpdate(sql,"Insert");
   }
  });

  btnInser.setBounds(309, 10, 98, 23);
  frmPersonTable.getContentPane().add(btnInser);
  
  JButton btnUdate = new JButton("Udate");
  btnUdate.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Actions-edit-redo-icon.png"));
  btnUdate.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    String sql="UPDATE person.user SET firstname='"+txtFname.getText()+"', lastname='"+txtLname.getText()+"', age='"+txtAge.getText()+"' WHERE id='"+txtID.getText()+"'";
    queryUpdate(sql, "Update");
   }
  });
  btnUdate.setBounds(309, 56, 98, 23);
  frmPersonTable.getContentPane().add(btnUdate);
  
  JButton btnDelete = new JButton("Delete");
  btnDelete.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Actions-edit-delete-icon.png"));
  btnDelete.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    String sql = "DELETE FROM person.user WHERE id='"+txtID.getText()+"'";
    queryUpdate(sql, "Delete");
   }
  });

  btnDelete.setBounds(309, 111, 98, 23);
  frmPersonTable.getContentPane().add(btnDelete);
  
  JScrollPane scrollPane = new JScrollPane();
  scrollPane.setBounds(10, 143, 414, 108);
  frmPersonTable.getContentPane().add(scrollPane);
  
  table = new JTable();
  table.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent arg0) {
    int row = table.getSelectedRow();
    TableModel model = (TableModel)table.getModel();
    txtID.setText(model.getValueAt(row, 0).toString());
    txtFname.setText(model.getValueAt(row, 1).toString());
    txtLname.setText(model.getValueAt(row, 2).toString());
    txtAge.setText(model.getValueAt(row, 3).toString());
    
   }
  });

  table.setModel(new DefaultTableModel(
   new Object[][] {
   },
   new String[] {
    "id", "first", "Last", "Age"
   }
  ));
  scrollPane.setViewportView(table);
  
  JLabel lblId = new JLabel("ID");
  lblId.setBounds(29, 14, 76, 14);
  frmPersonTable.getContentPane().add(lblId);
  
  JLabel lblLastname = new JLabel("LastName");
  lblLastname.setBounds(29, 81, 76, 14);
  frmPersonTable.getContentPane().add(lblLastname);
  
  JLabel lblFirstname = new JLabel("FirstName");
  lblFirstname.setBounds(29, 45, 76, 14);
  frmPersonTable.getContentPane().add(lblFirstname);
  
  JLabel lblAge = new JLabel("Age");
  lblAge.setBounds(29, 115, 76, 14);
  frmPersonTable.getContentPane().add(lblAge);
  
  txtAvg = new JTextField();
  txtAvg.setBounds(359, 279, 65, 20);
  frmPersonTable.getContentPane().add(txtAvg);
  txtAvg.setColumns(10);
  
  JLabel lblAvg = new JLabel("Avg");
  lblAvg.setBounds(303, 282, 46, 14);
  frmPersonTable.getContentPane().add(lblAvg);
  
  txtMax = new JTextField();
  txtMax.setBounds(57, 279, 86, 20);
  frmPersonTable.getContentPane().add(txtMax);
  txtMax.setColumns(10);
  
  JLabel lblMax = new JLabel("Max");
  lblMax.setBounds(10, 282, 46, 14);
  frmPersonTable.getContentPane().add(lblMax);
  
  txtMin = new JTextField();
  txtMin.setBounds(198, 279, 86, 20);
  frmPersonTable.getContentPane().add(txtMin);
  txtMin.setColumns(10);
  
  JLabel lblMin = new JLabel("Min");
  lblMin.setBounds(158, 282, 36, 14);
  frmPersonTable.getContentPane().add(lblMin);
  
  txtSum = new JTextField();
  txtSum.setBounds(57, 327, 86, 20);
  frmPersonTable.getContentPane().add(txtSum);
  txtSum.setColumns(10);
  
  JLabel lblSum = new JLabel("Sum");
  lblSum.setBounds(10, 330, 46, 14);
  frmPersonTable.getContentPane().add(lblSum);
 }
}
DBUtils.java

User.java

Back tohttp://giai-ma.blogspot.com/2016/05/insert-update-delete-swing-java-eclipse.html

05 May 2016

Insert Update Delete swing java eclipse with Getter constructor & Query Database


Create Database User




Create DBUtils  "Connect to database"



DBUtils.java
package controller;

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

public class DBUtils {

 private static Connection conn = null;
 
 public static Connection getConnection(){
  try {
   conn = DriverManager.getConnection("jdbc:mysql://localhost/person","root","1234567");
  } catch (Exception e) {
   e.printStackTrace();
  }
  return conn;
 }
}
NOTE: Add liblary connect database mysql
Create User   "getter & constructor"




User.java
package model;

public class User {

 private int id;
 private String firstName;
 private String lastName;
 private int age;

 public int getId() {
  return id;
 }

 public String getFirstName() {
  return firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public int getAge() {
  return age;
 }

 public User(int id, String firstName, String lastName, int age) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
 }

}
Create View

View.java
package view;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import controller.DBUtils;
import model.User;
import javax.swing.JLabel;
import javax.swing.ImageIcon;

public class View {

 private JFrame frmPersonTable;
 private JTextField txtID;
 private JTextField txtFname;
 private JTextField txtLname;
 private JTextField txtAge;
 public JTable table;

 private PreparedStatement stmt;
 private ResultSet rs;
 private Connection conn;
 
 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     View window = new View();
     window.frmPersonTable.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the application.
  */
 public View() {
  initialize();
  try {
   conn = DBUtils.getConnection();
  } catch (Exception e) {
   e.printStackTrace();
  }

  showTable();
 }

 public ArrayList<User> getArrayList(){
  ArrayList <User> list  = new ArrayList();
  try {
   stmt = conn.prepareStatement("Select * From person.user");
   rs = stmt.executeQuery();
   while(rs.next()){
    User user = new User(rs.getInt("id"),rs.getString("firstname"),rs.getString("lastname"),rs.getInt("age"));
    list.add(user);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  return list;
 }
 public void showTable(){
  ArrayList <User> list = getArrayList();
  DefaultTableModel model = (DefaultTableModel)table.getModel();
  Object[] cols = new Object[4];
  for (int i = 0; i < list.size(); i++) {
   cols[0] = list.get(i).getId();
   cols[1] = list.get(i).getFirstName();
   cols[2] = list.get(i).getLastName();
   cols[3] = list.get(i).getAge();
   model.addRow(cols);
  }
 }
 
 public void queryUpdate(String sql,String message){
  try {
   stmt = conn.prepareStatement(sql);
   if(stmt.executeUpdate()==1){
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.setRowCount(0);
    showTable();
    JOptionPane.showMessageDialog(null, message + " Successfully!");
   }
  } catch (SQLException se) {
   se.printStackTrace();
  }
 }
 /**
  * Initialize the contents of the frame.
  */
 private void initialize() {
  frmPersonTable = new JFrame();
  frmPersonTable.setTitle("Person Table\r\n");
  frmPersonTable.setBounds(100, 100, 450, 300);
  frmPersonTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frmPersonTable.getContentPane().setLayout(null);
  
  txtID = new JTextField();
  txtID.setBounds(137, 13, 127, 20);
  frmPersonTable.getContentPane().add(txtID);
  txtID.setColumns(10);
  
  txtFname = new JTextField();
  txtFname.setColumns(10);
  txtFname.setBounds(137, 44, 127, 20);
  frmPersonTable.getContentPane().add(txtFname);
  
  txtLname = new JTextField();
  txtLname.setColumns(10);
  txtLname.setBounds(137, 80, 127, 20);
  frmPersonTable.getContentPane().add(txtLname);
  
  txtAge = new JTextField();
  txtAge.setColumns(10);
  txtAge.setBounds(137, 114, 127, 20);
  frmPersonTable.getContentPane().add(txtAge);
  
  JButton btnInser = new JButton("Inser");
  btnInser.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\add-icon.png"));
  btnInser.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    String sql ="INSERT INTO person.user (firstname, lastname, age) "
       + "VALUES ('"+txtFname.getText()+"', '"+txtLname.getText()+"', '"+txtAge.getText()+"')";
    queryUpdate(sql,"Insert");
   }
  });

  btnInser.setBounds(309, 10, 98, 23);
  frmPersonTable.getContentPane().add(btnInser);
  
  JButton btnUdate = new JButton("Udate");
  btnUdate.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Actions-edit-redo-icon.png"));
  btnUdate.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    String sql="UPDATE person.user SET firstname='"+txtFname.getText()+"', lastname='"+txtLname.getText()+"', age='"+txtAge.getText()+"' WHERE id='"+txtID.getText()+"'";
    queryUpdate(sql, "Update");
   }
  });
  btnUdate.setBounds(309, 56, 98, 23);
  frmPersonTable.getContentPane().add(btnUdate);
  
  JButton btnDelete = new JButton("Delete");
  btnDelete.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Actions-edit-delete-icon.png"));
  btnDelete.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    String sql = "DELETE FROM person.user WHERE id='"+txtID.getText()+"'";
    queryUpdate(sql, "Delete");
   }
  });

  btnDelete.setBounds(309, 111, 98, 23);
  frmPersonTable.getContentPane().add(btnDelete);
  
  JScrollPane scrollPane = new JScrollPane();
  scrollPane.setBounds(10, 143, 414, 108);
  frmPersonTable.getContentPane().add(scrollPane);
  
  table = new JTable();
  table.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent arg0) {
    int row = table.getSelectedRow();
    TableModel model = (TableModel)table.getModel();
    txtID.setText(model.getValueAt(row, 0).toString());
    txtFname.setText(model.getValueAt(row, 1).toString());
    txtLname.setText(model.getValueAt(row, 2).toString());
    txtAge.setText(model.getValueAt(row, 3).toString());
    
   }
  });

  table.setModel(new DefaultTableModel(
   new Object[][] {
   },
   new String[] {
    "id", "first", "Last", "Age"
   }
  ));
  scrollPane.setViewportView(table);
  
  JLabel lblId = new JLabel("ID");
  lblId.setBounds(29, 14, 76, 14);
  frmPersonTable.getContentPane().add(lblId);
  
  JLabel lblLastname = new JLabel("LastName");
  lblLastname.setBounds(29, 81, 76, 14);
  frmPersonTable.getContentPane().add(lblLastname);
  
  JLabel lblFirstname = new JLabel("FirstName");
  lblFirstname.setBounds(29, 45, 76, 14);
  frmPersonTable.getContentPane().add(lblFirstname);
  
  JLabel lblAge = new JLabel("Age");
  lblAge.setBounds(29, 115, 76, 14);
  frmPersonTable.getContentPane().add(lblAge);
 }
}


display table


mouse click table


executeQuery



Insert Into  - () - Values



Update  - Set  - Where id = ? 


Delete From - Where id = ?


Download Icon:  http://www.iconarchive.com


Next >> Min Max Sum Avg - (Age)
Next : http://giai-ma.blogspot.com/2016/05/min-max-avg-sum-in-java-swing-eclipse.html 

27 April 2016

Upload images blob in mysql Java swing Eclipse Insert update delete search [Version 2]

Verson 2: Changes show images

DBConncetion.java
package DBConnection;

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

public class DBConnection {

 // Driver and URL
 private static final String DRIVER_JDBC = "com.mysql.jdbc.Driver";
 private static final String URL_DB = "jdbc:mysql://localhost/sinhvien";
 // Pass and User
 private static final String USER = "root";
 private static final String PASS = "1234567";

 private static Connection conn;

 public static Connection getConnection() {
  try {
   Class.forName(DRIVER_JDBC);
   conn = DriverManager.getConnection(URL_DB, USER, PASS);
  } catch (Exception e) {
    System.out.println("Error connection "+e);
  }

  return conn;
 }

}
NOTE: Add liblary connect database mysql
Main.java

Show images in Main.java


package Main;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import DBConnection.DBConnection;
import ThongTin.ChiTiet;
import ThongTin.view;
import javax.swing.JTextField;

public class Main {

 public JFrame frmMain;

 private Connection conn;
 private PreparedStatement stmt;
 private ResultSet rs;

 ChiTiet windown = new ChiTiet();
 view vew = new view();
 private JTable table;
 private JTextField txtSearch;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     Main window = new Main();
     window.frmMain.setVisible(true);
    } catch (Exception e) {
    }
   }
  });
 }

 /**
  * Create the application.
  */
 public Main() {
  initialize();
  try {
   conn = DBConnection.getConnection();
  } catch (Exception e) {
   // TODO: handle exception
  }
  showTable();

 }

 public void showTable() {

  // Name Column table
  Vector cols = new Vector();
  cols.addElement("ID");
  cols.addElement("Name");
  cols.addElement("Age");
  cols.addElement("Class");
  cols.addElement("Address");
  cols.addElement("Birthday");
  cols.addElement("Images");

  // Data table
  Vector data = new Vector();
  String sql = "Select * From sinhvien.sinhvien";
  try {
   stmt = conn.prepareStatement(sql);
   rs = stmt.executeQuery();
   int row = 0;
   while (rs.next()) {
    Vector sinhvien = new Vector();
    sinhvien.addElement(rs.getString("id"));
    sinhvien.addElement(rs.getString("name"));
    sinhvien.addElement(rs.getInt("age"));
    sinhvien.addElement(rs.getString("class"));
    sinhvien.addElement(rs.getString("address"));
    sinhvien.addElement(rs.getDate("birthday"));
    sinhvien.addElement(rs.getBytes("images"));

    data.add(sinhvien);
   }

  } catch (Exception e) {
   // TODO: handle exception
  }
  table.setModel(new DefaultTableModel(data, cols));
 }

 /**
  * Initialize the contents of the frame.
  */
 private void initialize() {
  frmMain = new JFrame();
  frmMain.setTitle("Main");
  frmMain.setBounds(660, 200, 641, 424);
  frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frmMain.getContentPane().setLayout(null);

  JScrollPane scrollPane = new JScrollPane();
  scrollPane.setBounds(10, 11, 605, 193);
  frmMain.getContentPane().add(scrollPane);

  JPanel panel_1 = new JPanel();
  panel_1.setBorder(new TitledBorder(null, "Button", TitledBorder.LEADING, TitledBorder.TOP, null, null));
  panel_1.setBounds(10, 215, 605, 77);
  frmMain.getContentPane().add(panel_1);
  panel_1.setLayout(null);

  JButton btnChiTiet = new JButton("Detail");
  btnChiTiet.setBounds(28, 25, 101, 23);
  panel_1.add(btnChiTiet);
  btnChiTiet.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\SinhVien\\icon\\detail-icon.png"));

  JButton btnReset = new JButton("Reset");
  btnReset.setBounds(494, 25, 101, 23);
  panel_1.add(btnReset);
  btnReset.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\SinhVien\\icon\\Reload-icon (1).png"));

  JButton btnDelete = new JButton("Delete");
  btnDelete.setBounds(383, 25, 101, 23);
  panel_1.add(btnDelete);
  btnDelete.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\SinhVien\\icon\\Actions-edit-delete-icon.png"));

  JButton btnView = new JButton("View");
  btnView.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    vew.frmView.setVisible(true);
   }
  });
  btnView.setIcon(
    new ImageIcon("C:\\Users\\Lonely\\workspace\\SinhVien\\icon\\Programming-Show-Property-icon (1).png"));
  btnView.setBounds(158, 25, 101, 23);
  panel_1.add(btnView);

  JPanel panel_2 = new JPanel();
  panel_2.setBorder(new TitledBorder(null, "Chuc nang", TitledBorder.LEADING, TitledBorder.TOP, null, null));
  panel_2.setBounds(10, 303, 605, 72);
  frmMain.getContentPane().add(panel_2);
  panel_2.setLayout(null);

  JComboBox comboBox = new JComboBox();
  comboBox.setModel(
    new DefaultComboBoxModel(new String[] {"All Search", "Name", "Age", "Class", "Address"}));
  comboBox.setBounds(26, 29, 103, 20);
  panel_2.add(comboBox);

  JButton btnSearch = new JButton("Search");
  btnSearch.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    Vector cols = new Vector();
    cols.addElement("ID");
    cols.addElement("Name");
    cols.addElement("Age");
    cols.addElement("Class");
    cols.addElement("Address");
    cols.addElement("Birthday");
    cols.addElement("Images");

    Vector data = new Vector();
    String Search = txtSearch.getText().trim();
    String Select = comboBox.getSelectedItem().toString();
    switch (Select) {
    case "All Search":
     String sql = "Select * From sinhvien.sinhvien";
     try {
      stmt = conn.prepareStatement(sql);
      rs = stmt.executeQuery();
      int row = 0;
      while (rs.next()) {
       Vector getData = new Vector();
       getData.addElement(rs.getString("id"));
       getData.addElement(rs.getString("name"));
       getData.addElement(rs.getInt("age"));
       getData.addElement(rs.getString("class"));
       getData.addElement(rs.getString("address"));
       getData.addElement(rs.getDate("birthday"));
       getData.addElement(rs.getBytes("images"));

       if (getData.toString().contains(Search)) {

        data.addElement(getData);
       }
      }

     } catch (Exception e1) {
      // TODO: handle exception
     }
     break;
    case "Name":
     try {
      String sqlName = "Select * from sinhvien.sinhvien Where name LIKE ?";
      stmt = conn.prepareStatement(sqlName);
      stmt.setString(1, txtSearch.getText() + "%");
      rs = stmt.executeQuery();
      while (rs.next()) {
       Vector getData = new Vector();
       getData.addElement(rs.getString("id"));
       getData.addElement(rs.getString("name"));
       getData.addElement(rs.getInt("age"));
       getData.addElement(rs.getString("class"));
       getData.addElement(rs.getString("address"));
       getData.addElement(rs.getDate("birthday"));
       getData.addElement(rs.getBytes("images"));

       data.addElement(getData);
      }

     } catch (Exception e2) {
      // TODO: handle exception
     }
     break;
    case "Class":
     try {
      String sqlName = "Select * from sinhvien.sinhvien Where class LIKE ?";
      stmt = conn.prepareStatement(sqlName);
      stmt.setString(1, "%"+txtSearch.getText() + "%");
      rs = stmt.executeQuery();
      while (rs.next()) {
       Vector getData = new Vector();
       getData.addElement(rs.getString("id"));
       getData.addElement(rs.getString("name"));
       getData.addElement(rs.getInt("age"));
       getData.addElement(rs.getString("class"));
       getData.addElement(rs.getString("address"));
       getData.addElement(rs.getDate("birthday"));
       getData.addElement(rs.getBytes("images"));

       data.addElement(getData);
      }

     } catch (Exception e2) {
      // TODO: handle exception
     }
     break;
    case "Age":
     try {
      String sqlName = "Select * from sinhvien.sinhvien Where age LIKE ?";
      stmt = conn.prepareStatement(sqlName);
      stmt.setInt(1, Integer.parseInt(txtSearch.getText()));
      rs = stmt.executeQuery();
      while (rs.next()) {
       Vector getData = new Vector();
       getData.addElement(rs.getString("id"));
       getData.addElement(rs.getString("name"));
       getData.addElement(rs.getInt("age"));
       getData.addElement(rs.getString("class"));
       getData.addElement(rs.getString("address"));
       getData.addElement(rs.getDate("birthday"));
       getData.addElement(rs.getBytes("images"));

       data.addElement(getData);
      }

     } catch (Exception e2) {
      // TODO: handle exception
     }
     break;
    case "Address":
     try {
      String sqlName = "Select * from sinhvien.sinhvien Where address LIKE ?";
      stmt = conn.prepareStatement(sqlName);
      stmt.setString(1, txtSearch.getText() + "%");
      rs = stmt.executeQuery();
      while (rs.next()) {
       Vector getData = new Vector();
       getData.addElement(rs.getString("id"));
       getData.addElement(rs.getString("name"));
       getData.addElement(rs.getInt("age"));
       getData.addElement(rs.getString("class"));
       getData.addElement(rs.getString("address"));
       getData.addElement(rs.getDate("birthday"));
       getData.addElement(rs.getBytes("images"));

       data.addElement(getData);
      }

     } catch (Exception e2) {
      // TODO: handle exception
     }
     break;

    }
    table.setModel(new DefaultTableModel(data, cols));
   }
}); btnSearch.setBounds(322, 28, 89, 23); panel_2.add(btnSearch); table = new JTable(); table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { int row = table.getSelectedRow(); windown.txtID.setText(table.getValueAt(row, 0).toString()); windown.txtName.setText(table.getValueAt(row, 1).toString()); windown.txtAge.setText(table.getValueAt(row, 2).toString()); windown.txtClass.setText(table.getValueAt(row, 3).toString()); windown.txtAddress.setText(table.getValueAt(row, 4).toString()); windown.txtBirthday.setDate((Date) table.getValueAt(row, 5)); vew.txtID.setText(table.getValueAt(row, 0).toString()); vew.txtName.setText(table.getValueAt(row, 1).toString()); vew.txtAge.setText(table.getValueAt(row, 2).toString()); vew.txtClass.setText(table.getValueAt(row, 3).toString()); vew.txtAddress.setText(table.getValueAt(row, 4).toString()); vew.txtBirthday.setText(table.getValueAt(row, 5).toString()); //convert object to byte[] java // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // ObjectOutputStream oos; // try { // oos = new ObjectOutputStream(bos); // oos.writeObject(table.getValueAt(row, 6)); // oos.flush(); // // byte[] imagedata = bos.toByteArray(); // ImageIcon format = new ImageIcon(imagedata); // // vew.lblImages.setIcon(format); // // oos.close(); // bos.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } int id = Integer.parseInt(vew.txtID.getText()); String sql = "Select * From sinhvien.sinhvien where id =?"; try { stmt = conn.prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); while (rs.next()) { byte[] imagedata = rs.getBytes("images"); ImageIcon format = new ImageIcon(imagedata); vew.lblImages.setIcon(format); } } catch (Exception e) { // TODO: handle exception } } }); scrollPane.setViewportView(table); txtSearch = new JTextField(); txtSearch.setBounds(156, 29, 132, 20); panel_2.add(txtSearch); txtSearch.setColumns(10); btnDelete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int id = Integer.parseInt(windown.txtID.getText()); String sql = "Delete From sinhvien.sinhvien Where id =?"; try { stmt = conn.prepareStatement(sql); stmt.setInt(1, id); int reponse = JOptionPane.showConfirmDialog(frmMain, "Do you want delete?", "Delete person", JOptionPane.YES_NO_OPTION); String message = "?"; switch (reponse) { case JOptionPane.YES_OPTION: message = "YES_OPTION"; stmt.executeUpdate(); break; case JOptionPane.NO_OPTION: message = "NO_OPTION"; break; case JOptionPane.CLOSED_OPTION: message = "CLOSED_OPTION"; break; default: message = "autre"; } JOptionPane.showMessageDialog(frmMain, "response: " + message); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Ban chua chon ID"); } showTable(); } }); btnReset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { showTable(); } }); btnChiTiet.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { windown.frmChiTiet.setVisible(true); // frmMain.setVisible(false); } }); } }
View.java

package ThongTin;

import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JFrame;

import DBConnection.DBConnection;
import Main.Main;

import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class View {

 public JFrame frmView;

 private Connection conn;
 private PreparedStatement stmt;
 private ResultSet rs;

 public JLabel txtID;
 public JLabel txtName;
 public JLabel txtClass;
 public JLabel txtAddress;
 public JLabel txtBirthday;
 public JLabel txtAge;
 public JLabel lblImages;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     View window = new View();
     window.frmView.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

 /**
  * Create the application.
  */
 public View() {
  initialize();
  try {
   conn = DBConnection.getConnection();
  } catch (Exception e) {
   // TODO: handle exception
  }

 }

 /**
  * Initialize the contents of the frame.
  */
 private void initialize() {
  frmView = new JFrame();
  frmView.setTitle("View");
  frmView.setBounds(50, 380, 536, 338);
  frmView.getContentPane().setLayout(null);

  JLabel lblName = new JLabel("Name:");
  lblName.setFont(new Font("Tahoma", Font.BOLD, 11));
  lblName.setBounds(219, 113, 46, 14);
  frmView.getContentPane().add(lblName);

  txtName = new JLabel("");
  txtName.setBounds(295, 113, 151, 14);
  frmView.getContentPane().add(txtName);

  JLabel lblId = new JLabel("ID:");
  lblId.setFont(new Font("Tahoma", Font.BOLD, 11));
  lblId.setBounds(219, 84, 46, 14);
  frmView.getContentPane().add(lblId);

  txtID = new JLabel("");
  txtID.setBounds(294, 84, 152, 14);
  frmView.getContentPane().add(txtID);

  txtBirthday = new JLabel("");
  txtBirthday.setBounds(295, 142, 151, 14);
  frmView.getContentPane().add(txtBirthday);

  txtClass = new JLabel("");
  txtClass.setBounds(295, 167, 151, 14);
  frmView.getContentPane().add(txtClass);

  txtAddress = new JLabel("");
  txtAddress.setBounds(294, 192, 151, 14);
  frmView.getContentPane().add(txtAddress);

  JLabel lblClass = new JLabel("Birthday:");
  lblClass.setFont(new Font("Tahoma", Font.BOLD, 11));
  lblClass.setBounds(219, 142, 78, 14);
  frmView.getContentPane().add(lblClass);

  JLabel lblAddress = new JLabel("Class:");
  lblAddress.setFont(new Font("Tahoma", Font.BOLD, 11));
  lblAddress.setBounds(219, 167, 78, 14);
  frmView.getContentPane().add(lblAddress);

  JLabel lblAddress_1 = new JLabel("Address:");
  lblAddress_1.setFont(new Font("Tahoma", Font.BOLD, 11));
  lblAddress_1.setBounds(219, 192, 78, 14);
  frmView.getContentPane().add(lblAddress_1);

  JPanel panel_1 = new JPanel();
  panel_1.setBorder(
    new TitledBorder(null, "Thong tin sinh vien", TitledBorder.LEADING, TitledBorder.TOP, null, null));
  panel_1.setBounds(175, 58, 335, 198);
  frmView.getContentPane().add(panel_1);
  panel_1.setLayout(null);

  JLabel lblAges = new JLabel("Age:");
  lblAges.setFont(new Font("Tahoma", Font.BOLD, 11));
  lblAges.setBounds(45, 162, 78, 14);
  panel_1.add(lblAges);

  txtAge = new JLabel("");
  txtAge.setBounds(119, 162, 151, 14);
  panel_1.add(txtAge);

  JPanel panel_2 = new JPanel();
  panel_2.setBorder(new TitledBorder(null, "Avatar", TitledBorder.LEADING, TitledBorder.TOP, null, null));
  panel_2.setBounds(10, 58, 155, 198);
  frmView.getContentPane().add(panel_2);
  panel_2.setLayout(null);

  lblImages = new JLabel("");
  lblImages.setBounds(10, 21, 135, 166);
  panel_2.add(lblImages);

  JLabel lblThongTinSinh = new JLabel("Thong Tin Sinh Vien Aptech FPT");
  lblThongTinSinh.setFont(new Font("Castellar", Font.BOLD, 19));
  lblThongTinSinh.setBounds(60, 11, 423, 36);
  frmView.getContentPane().add(lblThongTinSinh);

  JButton btnShow = new JButton("show");
  btnShow.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    show();
   }
  });
  btnShow.setBounds(50, 267, 89, 23);
  frmView.getContentPane().add(btnShow);
 }

 public void show() {
  // Data table
  int id = Integer.parseInt(txtID.getText());
  String sql = "Select * From sinhvien.sinhvien where id =?";
  try {
   stmt = conn.prepareStatement(sql);
   stmt.setInt(1, id);
   rs = stmt.executeQuery();
   while (rs.next()) {

    byte[] imagedata = rs.getBytes("images");
    ImageIcon format = new ImageIcon(imagedata);
    lblImages.setIcon(format);

   }

  } catch (Exception e) {
   // TODO: handle exception
  }

 }

}
Detail.java

package ThongTin;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.toedter.calendar.JDateChooser;

import DBConnection.DBConnection;
import Main.Main;

public class Detail {

 public JFrame frmChiTiet;
 public JTextField txtName;
 public JTextField txtAge;
 public JTextField txtClass;
 public JTextField txtAddress;
 private JTextField path;
 public JTextField txtID;
 public JDateChooser txtBirthday;

 String filename = null;
 BufferedImage bi;

 java.util.Date date;
 String dateInput;

 private Connection conn;
 private PreparedStatement stmt;
 private ResultSet rs;

 /**
  * Launch the application.
  */
 public static void main(String[] args) {
  EventQueue.invokeLater(new Runnable() {
   public void run() {
    try {
     Detail window = new Detail();
     window.frmChiTiet.setVisible(true);
    } catch (Exception e) {
    }
   }
  });
 }

 /**
  * Create the application.
  */
 public Detail() {
  initialize();
  try {
   conn = DBConnection.getConnection();
  } catch (Exception e) {
   // TODO: handle exception
  }
 }

 /**
  * Initialize the contents of the frame.
  */

 private void initialize() {
  frmChiTiet = new JFrame();
  frmChiTiet.setTitle("Detail");
  frmChiTiet.setBounds(50, 10, 517, 360);
  frmChiTiet.getContentPane().setLayout(null);

  JPanel panel = new JPanel();
  panel.setBorder(new TitledBorder(null, "Avatar", TitledBorder.LEADING, TitledBorder.TOP, null, null));
  panel.setBounds(10, 9, 194, 246);
  frmChiTiet.getContentPane().add(panel);
  panel.setLayout(null);

  path = new JTextField();
  path.setBounds(140, 278, 238, 20);
  frmChiTiet.getContentPane().add(path);
  path.setColumns(10);

  JLabel lblImages = new JLabel("");
  lblImages.setIcon(new ImageIcon("C:\\Users\\Lonely\\Desktop\\tv-smith-icon.png"));
  lblImages.setBounds(22, 24, 149, 198);
  panel.add(lblImages);

  JButton btnUpload = new JButton("Brown");
  btnUpload.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    JFileChooser fileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("images", "jpg", "png");
    fileChooser.setFileFilter(filter);

    int i = fileChooser.showOpenDialog(null);
    if (i == JFileChooser.APPROVE_OPTION) {
     File file = fileChooser.getSelectedFile();
     filename = file.getAbsolutePath();
     try {
      bi = ImageIO.read(file);
      ImageIcon icon = new ImageIcon(bi);
      lblImages.setIcon(icon);
     } catch (Exception e2) {
      // TODO: handle exception
     }
    }

   }
  });
  btnUpload.setBounds(25, 277, 89, 23);
  frmChiTiet.getContentPane().add(btnUpload);

  JPanel panel_2 = new JPanel();
  panel_2.setBorder(new TitledBorder(null, "Input", TitledBorder.LEADING, TitledBorder.TOP, null, null));
  panel_2.setBounds(204, 9, 287, 246);
  frmChiTiet.getContentPane().add(panel_2);
  panel_2.setLayout(null);

  JButton btnInsert = new JButton("Insert");
  btnInsert.setBounds(168, 201, 100, 34);
  panel_2.add(btnInsert);
  btnInsert.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\SinhVien\\icon\\add-icon.png"));

  txtAddress = new JTextField();
  txtAddress.setBounds(139, 170, 129, 20);
  panel_2.add(txtAddress);
  txtAddress.setColumns(10);

  txtName = new JTextField();
  txtName.setBounds(139, 46, 129, 20);
  panel_2.add(txtName);
  txtName.setColumns(10);

  txtBirthday = new JDateChooser();
  txtBirthday.setBounds(139, 139, 131, 20);
  panel_2.add(txtBirthday);

  txtClass = new JTextField();
  txtClass.setBounds(139, 108, 129, 20);
  panel_2.add(txtClass);
  txtClass.setColumns(10);

  txtAge = new JTextField();
  txtAge.setBounds(139, 77, 129, 20);
  panel_2.add(txtAge);
  txtAge.setColumns(10);

  txtID = new JTextField();
  txtID.setBounds(139, 15, 129, 20);
  panel_2.add(txtID);
  txtID.setColumns(10);

  JLabel lblAddress = new JLabel("Address");
  lblAddress.setBounds(29, 176, 75, 14);
  panel_2.add(lblAddress);

  JLabel lblNgaySinh = new JLabel("Ngay sinh");
  lblNgaySinh.setBounds(29, 147, 75, 14);
  panel_2.add(lblNgaySinh);

  JLabel lblLop = new JLabel("Lop");
  lblLop.setBounds(29, 113, 75, 14);
  panel_2.add(lblLop);

  JLabel lblTuoi = new JLabel("Tuoi");
  lblTuoi.setBounds(29, 82, 75, 14);
  panel_2.add(lblTuoi);

  JLabel lblTen = new JLabel("Ten");
  lblTen.setBounds(29, 51, 75, 14);
  panel_2.add(lblTen);

  JLabel lblId = new JLabel("ID");
  lblId.setBounds(29, 18, 46, 14);
  panel_2.add(lblId);

  JButton btnUpdate = new JButton("Update");
  btnUpdate.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    int id = Integer.parseInt(txtID.getText());
    String sql = "UPDATE sinhvien.sinhvien SET name=?, age=?, class=?, address=?,birthday=?, images=? WHERE id=?";

    date = txtBirthday.getDate();
    dateInput = new SimpleDateFormat("yyyy-MM-dd").format(date);

    path.setText(filename);
    try {
     // DATE
     File imgfile = new File(filename);
     FileInputStream fin = new FileInputStream(imgfile);

     stmt = conn.prepareStatement(sql);
     stmt.setString(1, txtName.getText());
     stmt.setInt(2, Integer.parseInt(txtAge.getText()));
     stmt.setString(3, txtClass.getText());
     stmt.setString(4, txtAddress.getText());
     stmt.setString(5, dateInput);
     stmt.setBinaryStream(6, fin, (int) imgfile.length());
     stmt.setInt(7, id);
     stmt.executeUpdate();
     System.out.println("Update OK");

    } catch (Exception e) {
     // TODO: handle exception
     System.out.println("Loi Update " + e);
    }

   }
  });
  btnUpdate.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\SinhVien\\icon\\Actions-edit-redo-icon.png"));
  btnUpdate.setBounds(29, 201, 108, 34);
  panel_2.add(btnUpdate);

  JButton btnReset = new JButton("Reset");
  btnReset.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    txtID.setText("");
    txtName.setText("");
    txtClass.setText("");
    txtAddress.setText("");
    txtAge.setText("");
    lblImages.setText("");
    path.setText("");
    txtBirthday.setDate(date);

   }
  });
  btnReset.setBounds(402, 277, 89, 23);
  frmChiTiet.getContentPane().add(btnReset);

  btnInsert.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    String sql = "INSERT INTO sinhvien.sinhvien (name, age, class, address, birthday, images) VALUES (?,?, ?, ?, ?, ?)";
    date = txtBirthday.getDate();
    dateInput = new SimpleDateFormat("yyyy-MM-dd").format(date);
    // Images
    FileInputStream fis;

    path.setText(filename);
    try {
     // DATE
     File imgfile = new File(filename);
     FileInputStream fin = new FileInputStream(imgfile);

     stmt = conn.prepareStatement(sql);
     stmt.setString(1, txtName.getText());
     stmt.setInt(2, Integer.parseInt(txtAge.getText()));
     stmt.setString(3, txtClass.getText());
     stmt.setString(4, txtAddress.getText());
     stmt.setString(5, dateInput);
     stmt.setBinaryStream(6, fin, (int) imgfile.length());

     stmt.executeUpdate();
     System.out.println("Insert ok");

    } catch (Exception e) {
     // TODO: handle exception
     System.out.println("Loi Insert: " + e);
    }
   }
  });

 }
}

Download import: https://drive.google.com/open?id=0BzClcKmnT6Ybc3RMdTFxSm93dlk
Back version 1 >> http://giai-ma.blogspot.com/2016/04/create-database-mysql-workbench.html

 

BACK TO TOP

Xuống cuối trang