By GokiSoft.com|
10:14 25/08/2021|
Java Advanced
[Share Code] Thêm/sửa/xoá sản phẩm + danh mục sản phẩm - lập trình kết nối CSDL mysql - Java 2 nâng cao - C2010G
- Nội dung kiến thức:
-> Quản lý sản phẩm (thêm/sửa/xoá) -> Product
-> Lấy danh sách category -> Show ra trong màn hình sản phẩm.
-> Login -> thanh cong -> Quản lý sản phẩm.
======================================================================
CSDL <-> Java App
CRUD -> Danh sach sp, them, sua, xoa
1) Tools -> java console -> Generate DB
- Ket noi database
- Do tables
- columns
- types
- Generate
- Class Object -> columns & type
- Modify -> danh sach, them, sua, xoa -> Version -> gen
======================================================================
#ProductModify.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson08;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Diep.Tran
*/
public class ProductModify {
public static List<Product> getProductList() {
List<Product> dataList = new ArrayList<>();
Connection conn = null;
PreparedStatement statement = null;
try {
//Mo ket noi toi database
conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
//Thuc hien truy van lay du lieu
String sql = "select product.*, category.name as category_name from product "
+ "left join category on product.category_id = category.id";
statement = conn.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Product p = new Product(
resultSet.getInt("id"),
resultSet.getString("title"),
resultSet.getString("thumbnail"),
resultSet.getString("content"),
resultSet.getString("created_at"),
resultSet.getString("updated_at"),
resultSet.getFloat("price")
);
Category c = new Category(
resultSet.getInt("category_id"),
resultSet.getString("category_name")
);
p.setCategory(c);
dataList.add(p);
}
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return dataList;
}
public static void save(Product p) {
if(p.getId() > 0) {
update(p);
} else {
insert(p);
}
}
private static void insert(Product p) {
Connection conn = null;
PreparedStatement statement = null;
try {
//Mo ket noi toi database
conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
//Thuc hien truy van lay du lieu
String sql = "insert into product(title, thumbnail, content, price, category_id, created_at, updated_at)"
+ " values (?, ?, ?, ?, ?, ?, ?)";
statement = conn.prepareStatement(sql);
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String strDate = dateFormat.format(date);
statement.setString(1, p.getTitle());
statement.setString(2, p.getThumbnail());
statement.setString(3, p.getContent());
statement.setFloat(4, p.getPrice());
statement.setInt(5, p.getCategory().getId());
statement.setString(6, strDate);
statement.setString(7, strDate);
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
private static void update(Product p) {
Connection conn = null;
PreparedStatement statement = null;
try {
//Mo ket noi toi database
conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
//Thuc hien truy van lay du lieu
String sql = "update product set title = ?, thumbnail = ?, content = ?, price = ?, category_id = ?, updated_at = ? where id = ?";
statement = conn.prepareStatement(sql);
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String strDate = dateFormat.format(date);
statement.setString(1, p.getTitle());
statement.setString(2, p.getThumbnail());
statement.setString(3, p.getContent());
statement.setFloat(4, p.getPrice());
statement.setInt(5, p.getCategory().getId());
statement.setString(6, strDate);
statement.setInt(7, p.getId());
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void delete(int id) {
Connection conn = null;
PreparedStatement statement = null;
try {
//Mo ket noi toi database
conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
//Thuc hien truy van lay du lieu
String sql = "delete from product where id = ?";
statement = conn.prepareStatement(sql);
statement.setInt(1, id);
statement.execute();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
#ProductFrame.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson08;
import java.awt.event.MouseListener;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.w3c.dom.events.MouseEvent;
/**
*
* @author Diep.Tran
*/
public class ProductFrame extends javax.swing.JFrame {
DataController dataMgr;
DefaultTableModel tableModel;
/**
* Creates new form ProductFrame
*/
public ProductFrame() {
initComponents();
tableModel = (DefaultTableModel) productTable.getModel();
dataMgr = DataController.getInstance();
dataMgr.getDataFromDB();
showCategoryCb();
display();
productTable.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
int position = productTable.getSelectedRow();
showRow(position);
}
@Override
public void mousePressed(java.awt.event.MouseEvent e) {
}
@Override
public void mouseReleased(java.awt.event.MouseEvent e) {
}
@Override
public void mouseEntered(java.awt.event.MouseEvent e) {
}
@Override
public void mouseExited(java.awt.event.MouseEvent e) {
}
});
}
int currentPos = -1;
private void showRow(int position) {
this.currentPos = position;
titleTxt.setText(dataMgr.getProductList().get(position).getTitle());
thumbnailTxt.setText(dataMgr.getProductList().get(position).getThumbnail());
priceTxt.setText(dataMgr.getProductList().get(position).getPrice() + "");
descriptionTxt.setText(dataMgr.getProductList().get(position).getContent());
int index = 0;
for (int i = 0; i < dataMgr.getCategoryList().size(); i++) {
if (dataMgr.getCategoryList().get(i).getId() == dataMgr.getProductList().get(position).getCategory().getId()) {
index = i;
}
}
categoryCb.setSelectedIndex(index);
}
private void showCategoryCb() {
for (Category category : dataMgr.getCategoryList()) {
categoryCb.addItem(category);
}
}
private void display() {
tableModel.setRowCount(0);
for (Product product : dataMgr.getProductList()) {
tableModel.addRow(new Object[]{
tableModel.getRowCount() + 1,
product.getTitle(),
product.getPrice(),
product.getCategory().getName()
});
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTextField3 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
titleTxt = new javax.swing.JTextField();
priceTxt = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
thumbnailTxt = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
descriptionTxt = new javax.swing.JTextArea();
jLabel6 = new javax.swing.JLabel();
categoryCb = new javax.swing.JComboBox<>();
saveBtn = new javax.swing.JButton();
deleteBtn = new javax.swing.JButton();
searchBtn = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
productTable = new javax.swing.JTable();
jLabel3.setText("Ten SP:");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Nhap Thong Tin San Pham"));
jLabel1.setText("Ten SP:");
jLabel2.setText("Gia SP:");
jLabel4.setText("Thumbnail:");
jLabel5.setText("Mo Ta:");
descriptionTxt.setColumns(20);
descriptionTxt.setRows(5);
jScrollPane1.setViewportView(descriptionTxt);
jLabel6.setText("Danh Muc:");
saveBtn.setText("Luu");
saveBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveBtnActionPerformed(evt);
}
});
deleteBtn.setText("Xoa");
deleteBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteBtnActionPerformed(evt);
}
});
searchBtn.setText("Tim Kiem");
searchBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(45, 45, 45)
.addComponent(titleTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addGap(25, 25, 25)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(thumbnailTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE)
.addComponent(priceTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE)
.addComponent(jScrollPane1)
.addComponent(categoryCb, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(searchBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(deleteBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(saveBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(37, 37, 37))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(titleTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(saveBtn))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(priceTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(deleteBtn))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(thumbnailTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(searchBtn))
.addGap(30, 30, 30)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(categoryCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(55, 55, 55))))
);
productTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"STT", "Ten SP", "Gia", "Danh Muc"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(productTable);
if (productTable.getColumnModel().getColumnCount() > 0) {
productTable.getColumnModel().getColumn(0).setResizable(false);
productTable.getColumnModel().getColumn(1).setResizable(false);
productTable.getColumnModel().getColumn(2).setResizable(false);
productTable.getColumnModel().getColumn(3).setResizable(false);
}
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
// TODO add your handling code here:
String title = titleTxt.getText();
String thumbnail = thumbnailTxt.getText();
String description = descriptionTxt.getText();
float price = Float.parseFloat(priceTxt.getText());
Category c = (Category) categoryCb.getSelectedItem();
Product p = null;
if (currentPos >= 0) {
//update
p = dataMgr.getProductList().get(currentPos);//p -> id: ton tai trong db
currentPos = -1;
p.setTitle(title);
p.setThumbnail(thumbnail);
p.setContent(description);
p.setPrice(price);
} else {
p = new Product(title, thumbnail, description, price);
}
p.setCategory(c);
ProductModify.save(p);
dataMgr.setProductList(ProductModify.getProductList());
display();
resetData();
}//GEN-LAST:event_saveBtnActionPerformed
private void deleteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteBtnActionPerformed
// TODO add your handling code here:
if(currentPos < 0) {
JOptionPane.showMessageDialog(rootPane, "Ban chua chon doi tuong xoa, vui long kiem tra lai");
return;
}
int option = JOptionPane.showConfirmDialog(rootPane, "Ban chac chan muon xoa san pham nay khong?");
System.out.println("option: " + option);
if (option == 0 && currentPos >= 0) {
ProductModify.delete(dataMgr.getProductList().get(currentPos).getId());
currentPos = -1;
dataMgr.setProductList(ProductModify.getProductList());
display();
resetData();
}
}//GEN-LAST:event_deleteBtnActionPerformed
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchBtnActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_searchBtnActionPerformed
private void resetData() {
titleTxt.setText("");
thumbnailTxt.setText("");
priceTxt.setText("");
descriptionTxt.setText("");
}
/**
* @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(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProductFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProductFrame.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 ProductFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<Category> categoryCb;
private javax.swing.JButton deleteBtn;
private javax.swing.JTextArea descriptionTxt;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField priceTxt;
private javax.swing.JTable productTable;
private javax.swing.JButton saveBtn;
private javax.swing.JButton searchBtn;
private javax.swing.JTextField thumbnailTxt;
private javax.swing.JTextField titleTxt;
// End of variables declaration//GEN-END:variables
}
#ProductFrame.form
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
<NonVisualComponents>
<Component class="javax.swing.JTextField" name="jTextField3">
</Component>
<Component class="javax.swing.JLabel" name="jLabel3">
<Properties>
<Property name="text" type="java.lang.String" value="Ten SP:"/>
</Properties>
</Component>
</NonVisualComponents>
<Properties>
<Property name="defaultCloseOperation" type="int" value="3"/>
</Properties>
<SyntheticProperties>
<SyntheticProperty name="formSizePolicy" type="int" value="1"/>
<SyntheticProperty name="generateCenter" type="boolean" value="false"/>
</SyntheticProperties>
<AuxValues>
<AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
</AuxValues>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jPanel1" max="32767" attributes="0"/>
<Component id="jScrollPane2" max="32767" attributes="0"/>
</Group>
<EmptySpace max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Component id="jPanel1" min="-2" max="-2" attributes="0"/>
<EmptySpace max="-2" attributes="0"/>
<Component id="jScrollPane2" min="-2" pref="170" max="-2" attributes="0"/>
<EmptySpace max="32767" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="jPanel1">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.TitledBorderInfo">
<TitledBorder title="Nhap Thong Tin San Pham"/>
</Border>
</Property>
</Properties>
<Layout>
<DimensionLayout dim="0">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" attributes="0">
<EmptySpace max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<Component id="jLabel1" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="45" max="-2" attributes="0"/>
<Component id="titleTxt" min="-2" pref="307" max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="0" attributes="0">
<Group type="103" groupAlignment="0" attributes="0">
<Component id="jLabel2" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel4" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel5" alignment="0" min="-2" max="-2" attributes="0"/>
<Component id="jLabel6" alignment="0" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace min="-2" pref="25" max="-2" attributes="0"/>
<Group type="103" groupAlignment="0" max="-2" attributes="0">
<Component id="thumbnailTxt" pref="307" max="32767" attributes="0"/>
<Component id="priceTxt" pref="307" max="32767" attributes="0"/>
<Component id="jScrollPane1" alignment="0" max="32767" attributes="0"/>
<Component id="categoryCb" max="32767" attributes="0"/>
</Group>
</Group>
</Group>
<EmptySpace pref="65" max="32767" attributes="0"/>
<Group type="103" groupAlignment="0" max="-2" attributes="0">
<Component id="searchBtn" max="32767" attributes="0"/>
<Component id="deleteBtn" alignment="0" max="32767" attributes="0"/>
<Component id="saveBtn" alignment="0" max="32767" attributes="0"/>
</Group>
<EmptySpace min="-2" pref="37" max="-2" attributes="0"/>
</Group>
</Group>
</DimensionLayout>
<DimensionLayout dim="1">
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="0" attributes="0">
<EmptySpace min="-2" pref="14" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="titleTxt" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="saveBtn" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="priceTxt" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="deleteBtn" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace type="separate" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel4" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="thumbnailTxt" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="searchBtn" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace min="-2" pref="30" max="-2" attributes="0"/>
<Group type="103" groupAlignment="3" attributes="0">
<Component id="jLabel6" alignment="3" min="-2" max="-2" attributes="0"/>
<Component id="categoryCb" alignment="3" min="-2" max="-2" attributes="0"/>
</Group>
<EmptySpace pref="24" max="32767" attributes="0"/>
<Group type="103" groupAlignment="0" attributes="0">
<Group type="102" alignment="1" attributes="0">
<Component id="jScrollPane1" min="-2" pref="63" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="28" max="-2" attributes="0"/>
</Group>
<Group type="102" alignment="1" attributes="0">
<Component id="jLabel5" min="-2" max="-2" attributes="0"/>
<EmptySpace min="-2" pref="55" max="-2" attributes="0"/>
</Group>
</Group>
</Group>
</Group>
</DimensionLayout>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="jLabel1">
<Properties>
<Property name="text" type="java.lang.String" value="Ten SP:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="titleTxt">
</Component>
<Component class="javax.swing.JTextField" name="priceTxt">
</Component>
<Component class="javax.swing.JLabel" name="jLabel2">
<Properties>
<Property name="text" type="java.lang.String" value="Gia SP:"/>
</Properties>
</Component>
<Component class="javax.swing.JTextField" name="thumbnailTxt">
</Component>
<Component class="javax.swing.JLabel" name="jLabel4">
<Properties>
<Property name="text" type="java.lang.String" value="Thumbnail:"/>
</Properties>
</Component>
<Component class="javax.swing.JLabel" name="jLabel5">
<Properties>
<Property name="text" type="java.lang.String" value="Mo Ta:"/>
</Properties>
</Component>
<Container class="javax.swing.JScrollPane" name="jScrollPane1">
<AuxValues>
<AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
<SubComponents>
<Component class="javax.swing.JTextArea" name="descriptionTxt">
<Properties>
<Property name="columns" type="int" value="20"/>
<Property name="rows" type="int" value="5"/>
</Properties>
</Component>
</SubComponents>
</Container>
<Component class="javax.swing.JLabel" name="jLabel6">
<Properties>
<Property name="text" type="java.lang.String" value="Danh Muc:"/>
</Properties>
</Component>
<Component class="javax.swing.JComboBox" name="categoryCb">
<Properties>
<Property name="model" type="javax.swing.ComboBoxModel" editor="org.netbeans.modules.form.editors2.ComboBoxModelEditor">
<StringArray count="0"/>
</Property>
</Properties>
<AuxValues>
<AuxValue name="JavaCodeGenerator_TypeParameters" type="java.lang.String" value="<Category>"/>
</AuxValues>
</Component>
<Component class="javax.swing.JButton" name="saveBtn">
<Properties>
<Property name="text" type="java.lang.String" value="Luu"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="saveBtnActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="deleteBtn">
<Properties>
<Property name="text" type="java.lang.String" value="Xoa"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="deleteBtnActionPerformed"/>
</Events>
</Component>
<Component class="javax.swing.JButton" name="searchBtn">
<Properties>
<Property name="text" type="java.lang.String" value="Tim Kiem"/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="searchBtnActionPerformed"/>
</Events>
</Component>
</SubComponents>
</Container>
<Container class="javax.swing.JScrollPane" name="jScrollPane2">
<AuxValues>
<AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
<SubComponents>
<Component class="javax.swing.JTable" name="productTable">
<Properties>
<Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.editors2.TableModelEditor">
<Table columnCount="4" rowCount="0">
<Column editable="false" title="STT" type="java.lang.Object"/>
<Column editable="false" title="Ten SP" type="java.lang.Object"/>
<Column editable="false" title="Gia" type="java.lang.Object"/>
<Column editable="false" title="Danh Muc" type="java.lang.Object"/>
</Table>
</Property>
<Property name="columnModel" type="javax.swing.table.TableColumnModel" editor="org.netbeans.modules.form.editors2.TableColumnModelEditor">
<TableColumnModel selectionModel="0">
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
<Title/>
<Editor/>
<Renderer/>
</Column>
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
<Title/>
<Editor/>
<Renderer/>
</Column>
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
<Title/>
<Editor/>
<Renderer/>
</Column>
<Column maxWidth="-1" minWidth="-1" prefWidth="-1" resizable="false">
<Title/>
<Editor/>
<Renderer/>
</Column>
</TableColumnModel>
</Property>
<Property name="tableHeader" type="javax.swing.table.JTableHeader" editor="org.netbeans.modules.form.editors2.JTableHeaderEditor">
<TableHeader reorderingAllowed="true" resizingAllowed="true"/>
</Property>
</Properties>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Form>
#Product.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson08;
/**
*
* @author Diep.Tran
*/
public class Product {
int id;
String title, thumbnail, content, createdAt, updatedAt;
float price;
Category category;//category_id => int.
public Product() {
}
public Product(String title, String thumbnail, String content, float price) {
this.title = title;
this.thumbnail = thumbnail;
this.content = content;
this.price = price;
}
public Product(String title, String thumbnail, String content, String createdAt, String updatedAt, float price) {
this.title = title;
this.thumbnail = thumbnail;
this.content = content;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.price = price;
}
public Product(int id, String title, String thumbnail, String content, String createdAt, String updatedAt, float price) {
this.id = id;
this.title = title;
this.thumbnail = thumbnail;
this.content = content;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@Override
public String toString() {
return "Product{" + "id=" + id + ", title=" + title + ", thumbnail=" + thumbnail + ", content=" + content + ", createdAt=" + createdAt + ", updatedAt=" + updatedAt + ", price=" + price + '}';
}
}
#DataController.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson08;
import java.util.ArrayList;
import java.util.List;
/**
* Singleton
* @author Diep.Tran
*/
public class DataController {
List<Product> productList;
List<Category> categoryList;
private static DataController instance = null;
private DataController() {
productList = new ArrayList<>();
categoryList = new ArrayList<>();
}
public synchronized static DataController getInstance() {
if(instance == null) {
instance = new DataController();
}
return instance;
}
public void getDataFromDB() {
productList = ProductModify.getProductList();
categoryList = CategoryModify.getCategoryList();
}
public List<Product> getProductList() {
return productList;
}
public void setProductList(List<Product> productList) {
this.productList = productList;
}
public List<Category> getCategoryList() {
return categoryList;
}
public void setCategoryList(List<Category> categoryList) {
this.categoryList = categoryList;
}
}
#Config.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson08;
/**
*
* @author Diep.Tran
*/
public interface Config {
String DB_URL = "jdbc:mysql://localhost:3306/C2010G";
String USERNAME = "root";
String PASSWORD = "";
}
#CategoryModify.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson08;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Diep.Tran
*/
public class CategoryModify {
public static List<Category> getCategoryList() {
List<Category> dataList = new ArrayList<>();
Connection conn = null;
PreparedStatement statement = null;
try {
//Mo ket noi toi database
conn = DriverManager.getConnection(Config.DB_URL, Config.USERNAME, Config.PASSWORD);
//Thuc hien truy van lay du lieu
String sql = "select * from category";
statement = conn.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Category c = new Category(
resultSet.getInt("id"),
resultSet.getString("name")
);
dataList.add(c);
}
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(ProductModify.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return dataList;
}
}
#Category.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package java2.lesson08;
/**
*
* @author Diep.Tran
*/
public class Category {
int id;
String name;
public Category() {
}
public Category(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)