How To Make a Products Manager Project With MySQL Database In Java Using NetBeans
In This Java and MySQL Project Tutorial We Will Use:
- Java Programming Language.
- MySQL Database.
- Netbeans IDE.
- flatuicolorpicker.com = to get flat colors.
- pixabay.com = to get images.
- pixabay.com = to get images.
- canva.com = to create images.
What We Will Do In This Project ? :
- design the products manager form using jpanels and borders.
- create a button to browse image and set the image path in a jtextfields, and display the image in a jlabel.
- create navigation buttons.
- create insert update, delete buttons.
Project Description And Source Code:
1 - Ceate DB Class (DB.java)
package java_products_manager;
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
// download the mysql connector -> https://dev.mysql.com/downloads/connector/j/
// create the database "product_db" on phpmyadmin ->
// http://127.0.0.1/phpmyadmin/server_databases.php?server=1
public class DB {
public static String servername = "localhost";
public static String username = "root";
public static String dbname = "product_db";
public static Integer portnumber = 3306;
public static String password = "";// no password
// create a function to create and get the connection
public static Connection getConnection()
{
MysqlDataSource datasource = new MysqlDataSource();
datasource.setServerName(servername);
datasource.setUser(username);
datasource.setDatabaseName(dbname);
datasource.setPortNumber(portnumber);
datasource.setPassword(password);
try {
return datasource.getConnection();
} catch (SQLException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}
2 - Create Product Class (Product.java)
package java_products_manager;
public class Product {
private Integer id;
private String name;
private String category;
private Integer quantity;
private Double price;
private String image_path;
public Product(Integer id, String name, String category, Integer quantity, Double price, String image_path) {
this.id = id;
this.name = name;
this.category = category;
this.quantity = quantity;
this.price = price;
this.image_path = image_path;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getImage_path() {
return image_path;
}
public void setImage_path(String image_path) {
this.image_path = image_path;
}
}
2 - Create Manage Products Frame (ManageProducts_Frame.java)
// create border
Border panel_border = BorderFactory.createMatteBorder(1, 1, 1, 1, Color.darkGray);
Border textField_border = BorderFactory.createMatteBorder(0, 0, 2, 0, Color.darkGray);
// arraylist of products
ArrayList<Product> productsArray = new ArrayList<>();
// int variable for navigation
int position = 0;
public ManageProducts_Frame() {
initComponents();
// center the form
this.setLocationRelativeTo(null);
// close image link > https://pixabay.com/vectors/cross-no-x-forbidden-closed-42928/
// show the close icon
displayImage("\\/Images/x.png", jLabel_close, 'r');
// set border
jPanel_Container.setBorder(panel_border);
jTextField_name.setBorder(textField_border);
jTextField_Quantity.setBorder(textField_border);
jTextField_price.setBorder(textField_border);
jTextField_imgPath.setBorder(textField_border);
// change the row height
jTable_products_.setRowHeight(35);
// populate the jtable with products
showProductsInTable();
}
// to populate the jtable with products we first need an arraylist of all products
// create a function that return an arraylist of products
public ArrayList<Product> getProductsList()
{
ArrayList<Product> list = new ArrayList<>();
String selectQuery = "SELECT * FROM `products`";
Statement st;
ResultSet rs;
try {
st = DB.getConnection().createStatement();
rs = st.executeQuery(selectQuery);
Product product;
while(rs.next())
{
product = new Product(rs.getInt("id"), rs.getString("name"),
rs.getString("category"), rs.getInt("quantity"),
rs.getDouble("price"), rs.getString("image_path"));
list.add(product);
}
} catch (SQLException ex) {
Logger.getLogger(ManageProducts_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
productsArray = list;
return list;
}
// create a function to show products in table
public void showProductsInTable()
{
ArrayList<Product> productsList = getProductsList();
DefaultTableModel model = (DefaultTableModel) jTable_products_.getModel();
// clear jtable
model.setRowCount(0);
Object[] row = new Object[6];// 6 the number of columns
for(int i = 0; i < productsList.size(); i++)
{
row[0] = productsList.get(i).getId();
row[1] = productsList.get(i).getName();
row[2] = productsList.get(i).getCategory();
row[3] = productsList.get(i).getQuantity();
row[4] = productsList.get(i).getPrice();
row[5] = productsList.get(i).getImage_path();
model.addRow(row);
}
}
// create a function to display product data by index
public void showProductData(int index)
{
jSpinner_id.setValue(productsArray.get(index).getId());
jTextField_name.setText(productsArray.get(index).getName());
jComboBox_Category.setSelectedItem(productsArray.get(index).getCategory());
jTextField_Quantity.setText(productsArray.get(index).getQuantity().toString());
jTextField_price.setText(productsArray.get(index).getPrice().toString());
jTextField_imgPath.setText(productsArray.get(index).getImage_path());
displayImage(productsArray.get(index).getImage_path(), jLabel_image,'a');
}
// create a function to check empty fields
public boolean checkEmptyFields()
{
String name = jTextField_name.getText().trim();
String quantity = jTextField_Quantity.getText().trim();
String price = jTextField_price.getText().trim();
String imagePath = jTextField_imgPath.getText().trim();
if(name.equals("") || quantity.equals("") || price.equals("") || imagePath.equals(""))
{
return false;
// if one or more fields are empty return false else return true
}
else
{
return true;
}
}
// create a function to dsplay image into jlabel
public void displayImage(String imgPath, JLabel label, char rsc)
{
ImageIcon imgIco;
// check if the image is from the project files
// if the image is from the resource rsc = 'r'
// if not you can put any character abcd 123467 .......
if(rsc == 'r')
{
imgIco = new ImageIcon(getClass().getResource(imgPath));
}
else
{
imgIco = new ImageIcon(imgPath);
}
Image img = imgIco.getImage().getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
label.setIcon(new ImageIcon(img));
}
// create a function to clear fields
public void clearFields()
{
jSpinner_id.setValue(0);
jTextField_name.setText("");
jTextField_Quantity.setText("");
jComboBox_Category.setSelectedIndex(0);
jTextField_price.setText("");
jTextField_imgPath.setText("");
jLabel_image.setIcon(null);
}
// close form
private void jLabel_closeMouseClicked(java.awt.event.MouseEvent evt) {
System.exit(0);
}
// button add a new product
private void jButton_add_ActionPerformed(java.awt.event.ActionEvent evt) {
if(checkEmptyFields())
{
String name = jTextField_name.getText();
String category = jComboBox_Category.getSelectedItem().toString();
Integer quantity = Integer.valueOf(jTextField_Quantity.getText());
Double price = Double.valueOf(jTextField_price.getText());
String img = jTextField_imgPath.getText();
String insertQuery = "INSERT INTO `products`(`name`, `category`, `quantity`, `price`, `image_path`) VALUES (?,?,?,?,?)";
try {
PreparedStatement ps = DB.getConnection().prepareStatement(insertQuery);
ps.setString(1, name);
ps.setString(2, category);
ps.setInt(3, quantity);
ps.setDouble(4, price);
ps.setString(5, img);
if(ps.executeUpdate() > 0)
{
showProductsInTable();
JOptionPane.showMessageDialog(null, "New Product Added Successfully", "Add Product", JOptionPane.INFORMATION_MESSAGE);
System.out.println("New Product Added");
}
else
{
JOptionPane.showMessageDialog(null, "Product Not Added", "Add Product", JOptionPane.ERROR_MESSAGE);
System.out.println("Some Error Message Here");
}
} catch (SQLException ex) {
Logger.getLogger(ManageProducts_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
JOptionPane.showMessageDialog(null, "One Or More Fields Are Empty", "Add Product", JOptionPane.ERROR_MESSAGE);
System.out.println("One Or More Fields Are Empty");
}
}
// Button edit the selected product
private void jButton_edit_ActionPerformed(java.awt.event.ActionEvent evt) {
if(checkEmptyFields())
{
Integer id = Integer.valueOf(jSpinner_id.getValue().toString());
String name = jTextField_name.getText();
String category = jComboBox_Category.getSelectedItem().toString();
Integer quantity = Integer.valueOf(jTextField_Quantity.getText());
Double price = Double.valueOf(jTextField_price.getText());
String img = jTextField_imgPath.getText();
String updateQuery = "UPDATE `products` SET `name`=?,`category`=?,`quantity`=?,`price`=?,`image_path`=? WHERE `id`=?";
try {
PreparedStatement ps = DB.getConnection().prepareStatement(updateQuery);
ps.setString(1, name);
ps.setString(2, category);
ps.setInt(3, quantity);
ps.setDouble(4, price);
ps.setString(5, img);
ps.setInt(6, id);
if(ps.executeUpdate() > 0)
{
showProductsInTable();
JOptionPane.showMessageDialog(null, "Product Updated", "Edit Product", JOptionPane.INFORMATION_MESSAGE);
//System.out.println("Product Updated");
}
else
{
JOptionPane.showMessageDialog(null, "Product Not Updated", "Edit Product", JOptionPane.ERROR_MESSAGE);
//System.out.println("Some Error Message Here");
}
} catch (SQLException ex) {
Logger.getLogger(ManageProducts_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
JOptionPane.showMessageDialog(null, "One Or More Fields Are Empty", "Edit Product", JOptionPane.ERROR_MESSAGE);
System.out.println("One Or More Fields Are Empty");
}
}
// Button remove the selected product
private void jButton_remove_ActionPerformed(java.awt.event.ActionEvent evt) {
if(Integer.valueOf(jSpinner_id.getValue().toString()) > 0)
{
Integer id = Integer.valueOf(jSpinner_id.getValue().toString());
String deleteQuery = "DELETE FROM `products` WHERE `id`=?";
try {
PreparedStatement ps = DB.getConnection().prepareStatement(deleteQuery);
ps.setInt(1, id);
// show a confirmation box before deleting the product
int confirm = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this product ?", "Remove Product", JOptionPane.YES_NO_OPTION);
if(confirm == JOptionPane.YES_OPTION)
{
if(ps.executeUpdate() > 0)
{
showProductsInTable();
JOptionPane.showMessageDialog(null, "Product Deleted Successfully", "Remove Product", JOptionPane.INFORMATION_MESSAGE);
System.out.println("Product Deleted");
clearFields();
}
else
{
JOptionPane.showMessageDialog(null, "Product Not Deleted, Make Sure The ID is Valid", "Remove Product", JOptionPane.ERROR_MESSAGE);
//System.out.println("Some Error Message Here");
}
}
} catch (SQLException ex) {
Logger.getLogger(ManageProducts_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
JOptionPane.showMessageDialog(null, "Product Not Deleted, Make Sure The ID is Valid", "Remove Product", JOptionPane.ERROR_MESSAGE);
}
}
// Button search product by id
private void jButton_search_ActionPerformed(java.awt.event.ActionEvent evt) {
if(checkEmptyFields())
{
int id = Integer.valueOf(jSpinner_id.getValue().toString());
String selectQuery = "SELECT * FROM `products` WHERE `id`="+id;
try {
Statement st = DB.getConnection().createStatement();
ResultSet rs = st.executeQuery(selectQuery);
if(rs.next())
{
jTextField_name.setText(rs.getString("name"));
jComboBox_Category.setSelectedItem(rs.getString("category"));
jTextField_Quantity.setText(rs.getString("quantity"));
jTextField_price.setText(String.valueOf(rs.getDouble("price")));
jTextField_imgPath.setText(rs.getString("image_path"));
displayImage(rs.getString("image_path"), jLabel_image,'a');
}
else
{
System.out.println("No Product With This ID");
}
} catch (SQLException ex) {
Logger.getLogger(ManageProducts_Frame.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
System.out.println("One Or More Fields Are Empty");
}
}
// Button browse and display image in jlabel
private void jButton_browse_ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser filechooser = new JFileChooser();
filechooser.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new FileNameExtensionFilter("*images", ".png","jpg",".jpeg");
filechooser.addChoosableFileFilter(filter);
if(filechooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)
{
File selectedImage = filechooser.getSelectedFile();
String image_path = selectedImage.getAbsolutePath();
displayImage(image_path, jLabel_image,'a');
jTextField_imgPath.setText(image_path);
System.out.println(image_path);
}
else
{
System.out.println("no file selected");
}
}
// display the selected products info
private void jTable_products_MouseClicked(java.awt.event.MouseEvent evt) {
int index = jTable_products_.getSelectedRow();
showProductData(index);
position = index;
}
// Button show the next product
private void jButton_next_ActionPerformed(java.awt.event.ActionEvent evt) {
position++;
if(position > productsArray.size() - 1)
{
position = productsArray.size() - 1;
}
showProductData(position);
jTable_products_.setRowSelectionInterval(position, position);
}
// Button show the previous product
private void jButton_previous_ActionPerformed(java.awt.event.ActionEvent evt) {
position--;
if(position < 0)
{
position = 0;
}
showProductData(position);
jTable_products_.setRowSelectionInterval(position, position);
}
// Button show the last product
private void jButton_last_ActionPerformed(java.awt.event.ActionEvent evt) {
position = productsArray.size()-1;
showProductData(position);
jTable_products_.setRowSelectionInterval(position, position);
}
// Button show the first product
private void jButton_first_ActionPerformed(java.awt.event.ActionEvent evt) {
position = 0;
showProductData(position);
jTable_products_.setRowSelectionInterval(position, position);
}
private void jTextField_QuantityKeyTyped(java.awt.event.KeyEvent evt) {
// allow only numbers
// or you can user jspinner
if(!Character.isDigit(evt.getKeyChar()))
{
evt.consume();
}
}
private void jTextField_priceKeyReleased(java.awt.event.KeyEvent evt) {
// allow double
try
{
Double.valueOf(jTextField_price.getText());
}
catch(NumberFormatException ex)
{
System.out.println(ex.getMessage());
jTextField_price.setText("");
}
}
OUTPUT:
if you want the source code click on the download button below
More Java Projects:
Download Projects Source Code