19 April 2016

Store swing in eclipse connect database insert update delete

Table 1


Table 2: Insert ID - Because id auto



Connecting.java 
package ConnectMaket;
import java.sql.Connection; import java.sql.DriverManager; public class Connecting { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/store"; static final String USER = "root"; static final String PASS = "1234567"; private static Connection conn; public static Connection getConnection() { try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); } catch (Exception e) { System.out.println("Error connecting.." + e); } return conn; } }
NOTE: Add liblary connect database mysql
Store.java 
package SuperMaket;

import java.awt.EventQueue;
import java.awt.Font;
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.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.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import ConnectMaket.Connecting;

public class Store {

 private JFrame frame; // De hien thi file InsertID.java
 private JTextField txtType;
 private JTextField txtPrice;
 private JTable tableStore;

 /**
  * Connecting database
  */
 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 {
     Store window = new Store();
     window.frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

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

 public void showTable() {
  // Title
  Vector cols = new Vector();
  cols.addElement("ID");
  cols.addElement("Type");
  cols.addElement("Company");
  cols.addElement("Price");
  // Data
  Vector data = new Vector();
  String sql = "SELECT * FROM store.store";
  try {
   stmt = conn.prepareStatement(sql);
   rs = stmt.executeQuery();
   while (rs.next()) {
    Vector store = new Vector();
    store.addElement(rs.getString("id"));
    store.addElement(rs.getString("type"));
    store.addElement(rs.getString("company"));
    store.addElement(rs.getString("price"));

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

 /**
  * Initialize the contents of the frame.
  */
 private void initialize() {
  frame = new JFrame();
  frame.setBounds(100, 100, 421, 327);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().setLayout(null);

  txtType = new JTextField();
  txtType.setBounds(131, 12, 133, 20);
  frame.getContentPane().add(txtType);
  txtType.setColumns(10);

  JComboBox comboBox = new JComboBox();
  comboBox.setModel(new DefaultComboBoxModel(new String[] { "Toshiba", "Sonny", "SamSung", "Apple", "Nokia" }));
  comboBox.setBounds(131, 43, 133, 20);
  frame.getContentPane().add(comboBox);

  txtPrice = new JTextField();
  txtPrice.setBounds(131, 74, 133, 20);
  frame.getContentPane().add(txtPrice);
  txtPrice.setColumns(10);

  JLabel lblType = new JLabel("Type:");
  lblType.setFont(new Font("Tahoma", Font.BOLD, 12));
  lblType.setBounds(10, 15, 111, 14);
  frame.getContentPane().add(lblType);

  JLabel lblCompany = new JLabel("Company:");
  lblCompany.setFont(new Font("Tahoma", Font.BOLD, 12));
  lblCompany.setBounds(10, 46, 111, 14);
  frame.getContentPane().add(lblCompany);

  JLabel lblPrice = new JLabel("Price:");
  lblPrice.setFont(new Font("Tahoma", Font.BOLD, 12));
  lblPrice.setBounds(10, 77, 111, 14);
  frame.getContentPane().add(lblPrice);

  JButton btnAdd = new JButton("Add");
  btnAdd.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    String sql = "INSERT INTO store.store (type, company, price) VALUES (?, ?, ?)";

    try {
     stmt = conn.prepareStatement(sql);

     stmt.setString(1, txtType.getText());
     stmt.setString(2, comboBox.getSelectedItem().toString());
     stmt.setString(3, txtPrice.getText());

     stmt.executeUpdate();
    } catch (Exception e) {
     // TODO: handle exception
    }
    showTable();
   }
  });
  btnAdd.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Swing003\\icon\\add-icon.png"));
  btnAdd.setBounds(274, 11, 112, 23);
  frame.getContentPane().add(btnAdd);

  JButton btnDelete = new JButton("Delete");
  btnDelete.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    String sql = "DELETE FROM store.store WHERE id=?";
    try {
     int row = tableStore.getSelectedRow();
     int id = Integer.parseInt(tableStore.getValueAt(row, 0).toString());

     int choice = JOptionPane.showConfirmDialog(null, "Are you sure?");
     if (choice != -1) {
      stmt = conn.prepareStatement(sql);
      //
      stmt.setInt(1, id);
      stmt.executeUpdate();

     }

    } catch (Exception e) {
     // TODO: handle exception
    }
    showTable();
   }
  });
  btnDelete.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Swing003\\icon\\Actions-edit-delete-icon.png"));
  btnDelete.setBounds(274, 73, 112, 23);
  frame.getContentPane().add(btnDelete);

  JButton btnUpdate = new JButton("Update");
  btnUpdate.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    String sql = "UPDATE store.store SET type=?, company=?, price=? WHERE id=?";
    try {
     int row = tableStore.getSelectedRow();
     int id = Integer.parseInt(tableStore.getValueAt(row, 0).toString());

     stmt = conn.prepareStatement(sql);

     stmt.setString(1, txtType.getText());
     stmt.setString(2, comboBox.getSelectedItem().toString());
     stmt.setString(3, txtPrice.getText());
     stmt.setInt(4, id);

     stmt.executeUpdate();
    } catch (Exception e) {
     // TODO: handle exception
    }
    showTable();
   }
  });
  btnUpdate.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Swing003\\icon\\Actions-edit-redo-icon.png"));
  btnUpdate.setBounds(274, 42, 112, 23);
  frame.getContentPane().add(btnUpdate);

  JScrollPane scrollPane = new JScrollPane();
  scrollPane.setBounds(10, 119, 377, 133);
  frame.getContentPane().add(scrollPane);

  tableStore = new JTable();
  tableStore.addMouseListener(new MouseAdapter() {
   @Override
   public void mouseClicked(MouseEvent arg0) {

    int row = tableStore.getSelectedRow();

    if (row != -1) {

     txtType.setText(tableStore.getValueAt(row, 1).toString());
     comboBox.setSelectedItem(tableStore.getValueAt(row, 2).toString());
     txtPrice.setText(tableStore.getValueAt(row, 3).toString());
    }
   }
  });
  tableStore
    .setModel(new DefaultTableModel(new Object[][] {}, new String[] { "ID", "Type", "Company", "Price" }));
  scrollPane.setViewportView(tableStore);

  JLabel lblCopyrightl = new JLabel("Copyright @ 2016 Version 1.0");
  lblCopyrightl.setFont(new Font("Vijaya", Font.BOLD, 15));
  lblCopyrightl.setBounds(239, 260, 169, 20);
  frame.getContentPane().add(lblCopyrightl);

  JButton btnUpdateId = new JButton("Insert ID");
  btnUpdateId.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent arg0) {
    InsertID window = new InsertID();
    window.frame.setVisible(true);
   }
  });
  btnUpdateId.setBounds(10, 258, 89, 23);
  frame.getContentPane().add(btnUpdateId);

  JButton btnRefresh = new JButton("Refresh");
  btnRefresh.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    showTable();
   }
  });
  btnRefresh.setBounds(115, 258, 89, 23);
  frame.getContentPane().add(btnRefresh);
 }
}

Display Jtable SELECT


Insert


Delete


Update


MouseClicked output values on jtable


Display screen Insert ID



InsertID.java
 package SuperMaket;

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

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import ConnectMaket.Connecting;

public class InsertID {

 JFrame frame;
 private JTextField txtType;
 private JTextField txtPrice;
 private JTextField txtID;

 // Connection to database
 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 {
     InsertID window = new InsertID();
     window.frame.setVisible(true);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }

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

 }

 /**
  * Initialize the contents of the frame.
  */
 private void initialize() {
  frame = new JFrame();
  frame.setBounds(100, 100, 384, 259);
  // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().setLayout(null);

  txtType = new JTextField();
  txtType.setBounds(104, 64, 123, 20);
  frame.getContentPane().add(txtType);
  txtType.setColumns(10);

  txtPrice = new JTextField();
  txtPrice.setBounds(104, 173, 123, 20);
  frame.getContentPane().add(txtPrice);
  txtPrice.setColumns(10);

  JComboBox comboBox = new JComboBox();
  comboBox.setModel(new DefaultComboBoxModel(new String[] { "Toshiba", "Sonny", "SamSung", "Apple", "Nokia" }));
  comboBox.setBounds(104, 122, 123, 20);
  frame.getContentPane().add(comboBox);

  JButton btnInsert = new JButton("Insert");
  btnInsert.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    String sql = "INSERT INTO store.store (id, type, company, price) VALUES (?, ?, ?, ?)";

    try {
     stmt = conn.prepareStatement(sql);

     stmt.setString(1, txtID.getText());
     stmt.setString(2, txtType.getText());
     stmt.setString(3, comboBox.getSelectedItem().toString());
     stmt.setString(4, txtPrice.getText());

     stmt.executeUpdate();
    } catch (Exception e1) {
     // TODO: handle exception
    }
   }

  });
  btnInsert.setIcon(new ImageIcon("C:\\Users\\Lonely\\workspace\\Swing003\\icon\\add-icon.png"));
  btnInsert.setBounds(250, 11, 89, 182);
  frame.getContentPane().add(btnInsert);

  JLabel lblType = new JLabel("Type");
  lblType.setBounds(26, 70, 46, 14);
  frame.getContentPane().add(lblType);

  JLabel lblCompany = new JLabel("Company");
  lblCompany.setBounds(26, 128, 46, 14);
  frame.getContentPane().add(lblCompany);

  JLabel lblPrice = new JLabel("Price");
  lblPrice.setBounds(26, 179, 46, 14);
  frame.getContentPane().add(lblPrice);

  txtID = new JTextField();
  txtID.setBounds(104, 11, 123, 20);
  frame.getContentPane().add(txtID);
  txtID.setColumns(10);

  JLabel lblId = new JLabel("ID:");
  lblId.setBounds(26, 17, 46, 14);
  frame.getContentPane().add(lblId);
 }

}


0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang