Java Products Manager Project With MySQL Database

How To Make a Products Manager Project With MySQL Database In Java Using NetBeans

Java Products Manager Project With MySQL Database


In this Java Tutorial we will see How To Make a Products Manager Project In Java 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.
- 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();
        
    }


display products in jtable


    // 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);
    }                                         


insert, update, delete buttons

// 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);
        }
    }                                               


search product by id



// 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"); 
        }
        
        
    }                                               


browse and display product image



   // 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 selected product info



  // display the selected products info
    private void jTable_products_MouseClicked(java.awt.event.MouseEvent evt) {                                            
        int index = jTable_products_.getSelectedRow();
        showProductData(index);
        position = index;
    }                                             


navigation buttons



// 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:

products manager project in java

products manager project in java




Javascript - Create Glass Bridge Game

How To Make The Glass Bridge Game From Squid Game In Javascript Using VS Code





In this JavaScript Tutorial we will see How to Make The Glass Stepping Stones Game or the glass bridge game From Squid Game In JavaScript and Visual Studio Code .

The Game Rules:
the player have to hop across a bridge of glasses with some glasses that breack easily.



Project Source Code:


<!DOCTYPE HTML>

<head>
<style>
.container{display: flex; flex-direction: row; flex-wrap: wrap;
justify-content: center; align-items: center}
.content, .start, .finish, .pic, .panels, .top, .bottom{
border: 1px solid lightslategray; box-sizing: border-box}
.start, .finish{width:120px; height: 220px; margin: 5px;
display: flex; flex-direction: row;
flex-wrap: wrap; justify-content: center; align-items: center}
.start, .finish, .panels{float: left;}
.panels{width: 850px; height: 220px; margin: 5px}
.top, .bottom{height: 110px; background-color: #2E2C28;display: flex;
flex-direction: row;
flex-wrap: wrap; justify-content: center; align-items: center}
.glass{width: 110px;height: 100px;border: 1px solid #fff;
background-color: #FFDF2B;
margin: 2px; background-size: 100% 100%;}
.glass:hover{background-color: darkgoldenrod}
#pic-start, #pic-finish{background-color: #FFDF2B; width: 100px; height: 100px;
background-size: 100% 100%;}
#pic-start{background-image: url('C://Users//1BestCsharp//Downloads//steps.png')}
#play-again{color: #fff; background-color: green; width:100%;
padding: 20px; border: 1px solid #fff}


</style>
</head>

<body>

<div class="container">

<div class="content">
<div class="start">
<div class="pic" id="pic-start">

</div>
</div>
<div class="panels">
<div class="top">
<button onclick="stepInThis(this)" class="glass g1"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g1"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g1"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g1"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g1"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g1"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g1"
disabled="disabled"></button>
</div>
<div class="bottom">
<button onclick="stepInThis(this)" class="glass g2"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g2"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g2"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g2"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g2"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g2"
disabled="disabled"></button>
<button onclick="stepInThis(this)" class="glass g2"
disabled="disabled"></button>
</div>
</div>
<div class="finish">
<div class="pic" id="pic-finish">
</div>
</div>

<div>
<button id="play-again" onclick="playagain()">Play Again</button>
</div>

</div>

</div>

<script>
glasses = document.getElementsByClassName('glass');
g1 = document.getElementsByClassName('g1');
g2 = document.getElementsByClassName('g2');
div_finish = document.getElementById('pic-finish');
step = "C://Users//1BestCsharp//Downloads//steps.png";
nostep = "C://Users//1BestCsharp//Downloads//nostep.png";
list = [step, nostep];
imagesOrder = [[]];
counter = 0;
won = true;
index = 0;


// create a function to enable buttons
function enableButton()
{
if(counter <= g1.length - 1)
{
g1[counter].disabled = false;
g2[counter].disabled = false;
}
}

// create a function to populate imagesOrder with random images
function getRandomImages()
{
for(let i = 0; i < g1.length; i++)
{
imagesOrder[i] = [];
// get random image
random_image = list[Math.floor(Math.random()*list.length)];

if(random_image == step)
{
imagesOrder[i][0] = random_image;
imagesOrder[i][1] = nostep;
}
else
{
imagesOrder[i][0] = random_image;
imagesOrder[i][1] = step;
}

console.log(imagesOrder[i][1]);
console.log(imagesOrder[i][0]);
console.log("-------------------");

}
}

function stepInThis(pic)
{
if(pic.classList.contains('g1'))
{
if(pic.disabled == false)
{
if(imagesOrder[counter][0] == nostep)
{
won = false;
}
if(counter == imagesOrder.length-1 && won == true)
{
div_finish.setAttribute("style",
"background-image: url('"+imagesOrder[counter][0]+"');");
alert("You've Won");
}
else if(won == false)
{
alert("You've Lost");
}

pic.setAttribute("style",
"background-image: url('"+imagesOrder[counter][0]+"');");
pic.disabled = true;
g2[counter].disabled = true;
counter++;
enableButton();
}
}
else if(pic.classList.contains('g2'))
{
if(pic.disabled == false)
{
if(imagesOrder[counter][1] == nostep)
{
won = false;
}
if(counter == imagesOrder.length-1 && won == true)
{
div_finish.setAttribute("style",
"background-image: url('"+imagesOrder[counter][1]+"');");
alert("You've Won");
}
else if(won == false)
{
alert("You've Lost");
}

pic.setAttribute("style",
"background-image: url('"+imagesOrder[counter][1]+"');");
pic.disabled = true;
g1[counter].disabled = true;
counter++;
enableButton();
}
}
}


// create a function to play again
function playagain()
{
won = true;
for(let i = 0; i < g1.length; i++)
{
g1[i].setAttribute("style","background-image: url();");
g2[i].setAttribute("style","background-image: url();");
g1[i].disabled = true;
g2[i].disabled = true;
}

counter = 0;
enableButton();
getRandomImages();
}


getRandomImages();
enableButton();



</script>

</body>

</html>
                                              


////// OUTPUT : 








download the source code