Add/Edit Product

Add Product

Above UI we are going to create by Java for adding staff in our Inventory management system desktop application. For that first we create a window and configure its title, size and color. Here we are creating a window at Top Level so we can add this window at the top of any other window.

    
             previousFrame.setVisible(false); 
	         this.previousFrame=previousFrame;
	         this.totalWinWidth = totalWinWidth;
	         this.totalWinHeight = totalWinHeight;	
             winWidth=totalWinWidth-totalWinWidth/20;
	         winHeight=totalWinHeight-totalWinHeight/20;

             Background main =  new Background(winWidth/50,winHeight/40,winWidth-winWidth/20,winHeight-winHeight/10);
		     main.setPreferredSize(new Dimension(winWidth-winWidth/20,winHeight-winHeight/10));
		 
		    frame = new JFrame("Product");	        
	        frame.addWindowListener(new java.awt.event.WindowAdapter() {
	            @Override
	            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
	            	 frame.dispose();// here [this] keyword means your current frame
	            	    //OR simply you can use this.setVisible(false); instead of this.dispose();
	            	 previousFrame.setVisible(true);
	            }
	        });
	        frame.pack();
			Utils.centeredFrame(frame, winWidth,winHeight, "Add Product");
	        frame.setVisible(true);
	        frame.setResizable(false);

	        Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
            frame.setCursor(cursor);	        
	        Container mainContainer=frame.getContentPane();
	        mainContainer.setBackground(Color.gray);



    

Here is our class Background:

    
    
    public class Background extends JComponent {
	
	int width, height,setX,setY;

    public Background (int setX,int setY,int width, int height) {
    	this.width=width;
    	this.height=height;
    	this.setX=setX;
    	this.setY=setY;
    	
       setSize(width, height);
    }
	
    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        g2.setPaint(Color.white);
        
        
        
        
        RenderingHints qualityHints = new RenderingHints(
        		  RenderingHints.KEY_ANTIALIASING,
        		  RenderingHints.VALUE_ANTIALIAS_ON );
        		qualityHints.put(
        		  RenderingHints.KEY_RENDERING,
        		  RenderingHints.VALUE_RENDER_QUALITY );
        		g2.setRenderingHints( qualityHints );

        //g2.setStroke(new BasicStroke(2.0f));

        double x = setX;
        double y = setY;
        double w = width;
        double h = height;
        RoundRectangle2D round=new RoundRectangle2D.Double(x, y, w, h, 80, 80);
        g2.fill(round);
        
       

    }

    
}


    

Here we create Labels and Text Fields.

    
            JPanel panel = new JPanel();
	        panel.setLayout(null);
		    panel.setOpaque(false);
		    panel.setBackground(Color.BLACK);
		    panel.setSize(new Dimension(winWidth-winWidth/20,winHeight-winHeight/10));
		    panel.setLocation(winWidth/50,winHeight/40);
		    mainContainer.add(panel,BorderLayout.CENTER);
		    
		    JComponent jcomponent=new Background(winWidth/50,winHeight/40,winWidth-winWidth/20,winHeight-winHeight/10);// 
	        mainContainer.add(jcomponent,BorderLayout.CENTER);
	       	
	        
	        JPanel header =  Utils.createPanel(winWidth*91/100,winHeight/10,new Point(winWidth/50,winHeight/40), true,"");
	        panel.add(header,BorderLayout.NORTH);
	        header.setLayout(new BorderLayout());

	        JPanel ledtside =  Utils.createPanel(winWidth/3,winHeight*7/10,new Point(winWidth/50,winHeight/6), true,"Action");
	        panel.add(ledtside,BorderLayout.NORTH);
	        ledtside.setLayout(null);
	        
	        JPanel rightside =  Utils.createPanel(winWidth*57/100,winHeight*7/10,new Point(winWidth/3+winWidth/30,winHeight/6), true,"Staff Details");
	        panel.add(rightside,BorderLayout.WEST);
	        rightside.setLayout(null);

	        
	        heading=new JLabel();
	        heading.setText("Add/Edit Product");
	        heading.setForeground(Color.black);
	        heading.setFont(new Font("Lucida",Font.PLAIN,40));
	        heading.setSize(new Dimension(winWidth/3,winHeight/10));
	        //heading.setLocation(winWidth/2-winWidth/6,0);
	        heading.setHorizontalAlignment(JLabel.CENTER);
	        header.add(heading,BorderLayout.CENTER);
	        
	        Border loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);

	        
	        TitledBorder productnamrTitle = BorderFactory.createTitledBorder(loweredetched, "Product Name");
	        productnamrTitle.setTitleJustification(TitledBorder.LEFT);
	        
	        TitledBorder productCategoryTitle = BorderFactory.createTitledBorder(loweredetched, "Category");
	        productCategoryTitle.setTitleJustification(TitledBorder.LEFT);
	        
	        TitledBorder productPricetitle = BorderFactory.createTitledBorder(loweredetched, "Price");
	        productPricetitle.setTitleJustification(TitledBorder.LEFT);
	        
	        TitledBorder searchTittle = BorderFactory.createTitledBorder(loweredetched, "Search");
	        searchTittle.setTitleJustification(TitledBorder.LEFT);
	        
	        TitledBorder quantityTittle = BorderFactory.createTitledBorder(loweredetched, "Quantity");
	        quantityTittle.setTitleJustification(TitledBorder.LEFT);
	        
            TitledBorder gstdTittled = BorderFactory.createTitledBorder(loweredetched, "Gst");
            gstdTittled.setTitleJustification(TitledBorder.LEFT);
            
            
            productName=new JLabel();
            productName.setText("Enter Product Name");
            productName.setForeground(Color.black);
            productName.setFont(new Font("Lucida",Font.PLAIN,12));
            productName.setSize(new Dimension(winWidth/3,winHeight/10));
            productName.setLocation(30, 0); 
	        ledtside.add(productName);
	        

	        productNametextField = new JTextField();
	        productNametextField.setSize(new Dimension(winWidth*3/10,winHeight/15));
	        productNametextField.setLocation(30,winHeight/15);	
	        productNametextField.setBorder(productnamrTitle);
	        ledtside.add(productNametextField,BorderLayout.SOUTH);
	        
	        
	        productCategory=new JLabel();
	        productCategory.setText("Enter Product Category");
	        productCategory.setForeground(Color.black);
	        productCategory.setFont(new Font("Lucida",Font.PLAIN,12));
	        productCategory.setSize(new Dimension(winWidth/3,winHeight/10));
	        productCategory.setLocation(30, winHeight/10+winHeight/100); 
	        ledtside.add(productCategory);
	       

	        productCategorytextField = new JTextField();
	        productCategorytextField.setSize(new Dimension(winWidth*3/10,winHeight/15));
	        productCategorytextField.setLocation(30,winHeight/6+winHeight/100);	
	        productCategorytextField.setBorder(productCategoryTitle);
	        ledtside.add(productCategorytextField,BorderLayout.SOUTH);


	        productPrice=new JLabel();
	        productPrice.setText("Enter Contact No");
	        productPrice.setForeground(Color.black);
	        productPrice.setFont(new Font("Lucida",Font.PLAIN,12));
	        productPrice.setSize(new Dimension(winWidth/3,winHeight/10));
	        productPrice.setLocation(30, winHeight/5+winHeight/70); 
	        ledtside.add(productPrice);
	        

	        productPriceTextfield = new JTextField();
	        productPriceTextfield.setSize(new Dimension(winWidth*3/10,winHeight/15));
	        productPriceTextfield.setLocation(30,winHeight/4+winHeight/30);	
	        productPriceTextfield.setBorder(productPricetitle);
	        ledtside.add(productPriceTextfield,BorderLayout.SOUTH);
	      
	        productQunatity=new JLabel();
	        productQunatity.setText("Enter Product Quantity");
	        productQunatity.setForeground(Color.black);
	        productQunatity.setFont(new Font("Lucida",Font.PLAIN,12));
	        productQunatity.setSize(new Dimension(winWidth/3,winHeight/10));
	        productQunatity.setLocation(30, winHeight/3); 
	        ledtside.add(productQunatity);
	        

	        productQuantityTextField = new JTextField();
	        productQuantityTextField.setSize(new Dimension(winWidth*3/10,winHeight/15));
	        productQuantityTextField.setLocation(30,winHeight/3+winHeight/15);	
	        productQuantityTextField.setBorder(quantityTittle);
	        ledtside.add(productQuantityTextField,BorderLayout.SOUTH);
	        
	        
	        productGst=new JLabel();
	        productGst.setText("Enter Gst");
	        productGst.setForeground(Color.black);
	        productGst.setFont(new Font("Lucida",Font.PLAIN,12));
	        productGst.setSize(new Dimension(winWidth/3,winHeight/10));
	        productGst.setLocation(30, winHeight/2-winHeight/18); 
	        ledtside.add(productGst);
	        
	        productGstTextField = new JTextField();
	        productGstTextField.setSize(new Dimension(winWidth*3/10,winHeight/15));
	        productGstTextField.setLocation(30, winHeight/2+ winHeight/60);	
	        productGstTextField.setBorder(gstdTittled);
	        ledtside.add(productGstTextField,BorderLayout.SOUTH);
	        
	        
    

Here we Define "ADD PRODUCT" Button UI.

    
            JButton addproductButton = new JButton(new ImageIcon(((new ImageIcon("images/button37.png")).getImage()).getScaledInstance(200, 50, java.awt.Image.SCALE_SMOOTH)));
	        addproductButton.setContentAreaFilled(false);
	        addproductButton.setBorder(null);
	        addproductButton.setText("Add Product");
	        addproductButton.setForeground(Color.white);
	        addproductButton.setFont(new Font("Lucida",Font.PLAIN,16));
	        addproductButton.setHorizontalTextPosition(JButton.CENTER);
	        addproductButton.setVerticalTextPosition(JButton.CENTER);
	        addproductButton.setBounds(winWidth/6-100,winHeight/2+ winHeight/9,200,50);  
	        addproductButton.setVisible(true);  
	        addproductButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

	        ledtside.add(addproductButton);
        
    

We have created a Database named "invertory.db", lets connect that database and put that code in seperate class "SQLiteJDBCDriverConnection" because we are going to use it multiple time in our project.

    
    public class SQLiteJDBCDriverConnection {

        public static Connection connect1() {

            try {
                     // SQLite connection string
                    Class.forName("org.sqlite.JDBC");
            } catch (ClassNotFoundException ex) {
                 Logger.getLogger(SQLiteJDBCDriverConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
            String url = "jdbc:sqlite:inventry.db";
            Connection conn = null;

            try {
                    conn = DriverManager.getConnection(url);
            } catch (SQLException e) {
                     System.out.println(e.getMessage());
            }
        return conn;
  
  
	}



}
                

Here's logic of "ADD PRODUCT" Button click functionality.

    


    addproductButton.addActionListener(new ActionListener() {
	            @Override
	            public void actionPerformed(ActionEvent ae) {
	            	
	            	String productName="";
	            	String productCategory="";
	            	String productPriceString="";
	            	String productQuantity="";
	            	String productGstString="";

	               String var="";
          		   if(productNametextField.getText().isEmpty()){
          			   var=var+"Product Name shouldnot be Empty, ";
          			   
          		   }else{
          			 productName=productNametextField.getText().toString();
          		   }
          		   
          		   
          		 if(productCategorytextField.getText().isEmpty()){
        			   var=var+"Category shouldnot be Empty, ";
        			   
        		   }else{
        			   productCategory=productCategorytextField.getText().toString();
        		   }
          		if(productPriceTextfield.getText().isEmpty()){
     			   var=var+"Price shouldnot be Empty, ";
     			   
     		   }else{
     			  productPriceString=productPriceTextfield.getText().toString();
     		   }
          		if(productQuantityTextField.getText().isEmpty()){
      			   var=var+"quantity shouldnot be Empty ";
      			   
      		   }else{
      			 productQuantity=productQuantityTextField.getText().toString();
      		   }
          		if(productGstTextField.getText().isEmpty()){
       			   var=var+"Gst shouldnot be Empty ";
       			   
       		   }else{
       			productGstString=productGstTextField.getText().toString();
       		   } 
          		   
          		   
          		   if(var==""){
          			 String sql = "SELECT value FROM system_info WHERE key = 'PRODUCT_LAST_COUNT'";
	            	   try (Connection conn = SQLiteJDBCDriverConnection.connect1();
	            	        Statement stmt  = conn.createStatement();
	            	        ResultSet rs    = stmt.executeQuery(sql)){
	            		   int  s = rs.getInt("value");
	            		   String staff_id_String = "PD";
	            		   DecimalFormat df = new DecimalFormat("000");
	            		   String generatedID=staff_id_String+df.format(s);
	            		   stmt.close();
	            		   conn.close();
	            		   
	            		  boolean isSussessFullEntered=tableIntryField(generatedID,productName,productCategory,productQuantity,productPriceString,productGstString);
	            		  if(isSussessFullEntered){
	            			  
	            			  updateLastCount(s+1);
	            			  productNametextField.setText("");
	            			  productCategorytextField.setText("");
	            			  productPriceTextfield.setText("");
	            			  productQuantityTextField.setText("");
	            			  productGstTextField.setText("");

	            			  displaylistToTable(table,getTableListData());

	               			 JOptionPane.showMessageDialog(frame, "Successfull Enterd");  
	            		  }else{
		               			 JOptionPane.showMessageDialog(frame, "Not Enterd");
	            		  }
	            	
	            	   } catch (SQLException e) {
	            	       System.out.println(e.getMessage());
	            	   }
	            	
          		   }else{
          			 JOptionPane.showMessageDialog(frame, var);

          		   }
	          	
	            }
	        });	        


    public boolean tableIntryField(String generatedID, String nameString, String categoryString, String productCount,
			String productprice,String gst) {
		 
		 		conn=SQLiteJDBCDriverConnection.connect1();
	            boolean issuccess=false;
	            Statement stmt = null;
	            int action;

		        String sql = "INSERT INTO product (product_id, product_name, product_category, product_count,product_price, product_gst) " +
                        "VALUES (?,?,?,?,?,?);"; 
        
		        PreparedStatement pst  = null;
		        ResultSet rs = null;
		        try {
		                pst = conn.prepareStatement(sql);
		                pst.setString(1, generatedID);
		                pst.setString(2, nameString);
			            pst.setString(3, categoryString);
			            pst.setString(4, productCount);
			            pst.setString(5, productprice);
			            pst.setString(6, gst);

			            action = pst.executeUpdate();
			            if(action>0){
					    	   issuccess= true;
			 
					       }else{
					    	   issuccess= false;

					       }
			           
		            } catch (Exception a) {
		                a.printStackTrace();
		            } finally {
		                if(rs != null){
		                     try{
		                          rs.close();
		                     } catch(Exception e){
		                         e.printStackTrace();
		                     }
		                }
		                if(pst != null){
		                    try{
		                        pst.close();
		                    } catch(Exception e){
		                        e.printStackTrace();
		                    }
		                }
		            }
		        
		       return issuccess;
	}


        
    

Now Create a Search UI for already added Product in product table. First we create a entry box to search Product with Product Id and Product Name.

    
        
                search=new JLabel();
		        search.setText("Search product");
		        search.setForeground(Color.black);
		        productQunatity.setFont(new Font("Lucida",Font.PLAIN,12));
		        search.setSize(new Dimension(winWidth/4,winHeight/10));
		        search.setLocation(30, 5); 
		        rightside.add(search);
		        
		        
		        searchTextField = new JTextField();
		        searchTextField.setSize(new Dimension(winWidth/4,winHeight/15));
		        searchTextField.setLocation(30,60);	
		        searchTextField.setBorder(searchTittle);
		        rightside.add(searchTextField);
		        //searchTextField.setCursor(arg0);
		        
				
		        searchTextField.getDocument().addDocumentListener(new DocumentListener() {
			         @Override
			         public void insertUpdate(DocumentEvent e) {
			            search(searchTextField.getText());
			            
			         }
			         @Override
			         public void removeUpdate(DocumentEvent e) {
			            search(searchTextField.getText());
			         }
			         @Override
			         public void changedUpdate(DocumentEvent e) {
			            search(searchTextField.getText());
			         }
			         public void search(String str) {
			            if (str.length() == 0) {
			  			  displaylistToTable(table,getTableListData());
			            } else {
			            	defaultdataModel.setRowCount(0);
				  			  displaylistToTable(table,getselectedTableListData(str));
			            }
			         }
			      });
		        
		        
        
    

Create a Product table UI.

    

              JTableHeader tableHeader21 = table.getTableHeader();
			  tableHeader21.setDefaultRenderer(new KeepSortIconHeaderRenderer(tableHeader21.getDefaultRenderer()));
			  
			  
			  JScrollPane pane = new JScrollPane(table);
		      pane.setLocation(30, 150);
		      pane.setSize(new Dimension(winWidth*53/100,winHeight/2));
			  rightside.add(pane);			  
			  table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
		          public void valueChanged(ListSelectionEvent event) {
		              
		              if(null!=editButton && null!=deleteButton){
		            	  editButton.setVisible(true);
		            	  deleteButton.setVisible(true);

		              }
		              
		              
		          }
		      });



public void displaylistToTable(JTable table,ArrayList productList){
	 
	 defaultdataModel=new DefaultTableModel();
	 Object []row=new Object[6];

	 defaultdataModel.setColumnIdentifiers(new Object[]{"ID","Name","Category","Price","Count","Gst"});
	 
	 for (int i = 0; i < productList.size(); i++) {

		 row[0]=productList.get(i).getId();
		 row[1]=productList.get(i).getProductName();
		 row[2]=productList.get(i).getProductCategory();
		 row[3]=productList.get(i).getProductPrice();
		 row[4]=productList.get(i).getProductCount();
		 row[5]=productList.get(i).getProductGst();

		 defaultdataModel.addRow(row);


	}
	 defaultdataModel.isCellEditable(0, 0);
	 
	
	 table.setModel(defaultdataModel);
	 DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();

	   centerRenderer.setHorizontalAlignment( JLabel.CENTER );
	  table.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );
	  table.getColumnModel().getColumn(1).setCellRenderer( centerRenderer );
	  table.getColumnModel().getColumn(2).setCellRenderer( centerRenderer );
	  table.getColumnModel().getColumn(3).setCellRenderer( centerRenderer );
	  table.getColumnModel().getColumn(4).setCellRenderer( centerRenderer );
	  table.getColumnModel().getColumn(5).setCellRenderer( centerRenderer );
	  table.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
	  table.getColumnModel().getColumn(1).setPreferredWidth(200);
      table.getColumnModel().getColumn(2).setPreferredWidth(150);
       table.setRowHeight(30);


	 
}
 


    

Here logic to get data from database and show it in table.

    

    public ArrayList getTableListData(){
	 ArrayList productList=new ArrayList();
		 
		  ResultSet rs;
		  String query = "SELECT * FROM product;" ;
	      conn = SQLiteJDBCDriverConnection.connect1();
	     
	      
	      Statement stat = null;
			try {
				stat = conn.createStatement();
				 rs = stat.executeQuery(query);
				 ProductData productData;
				 while(rs.next()){
					 productData=new ProductData(rs.getString("product_id"), rs.getString("product_name"), rs.getString("product_category"), rs.getString("product_price"), rs.getString("product_count"), rs.getString("product_gst"));
					 productList.add(productData);
				 }
				 
				   

			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
      

		  return productList;
		 
	 }
 

   

    

Create a "EDITE" and "DELETE" button UI it will appears when click on table row.

    

                //    Edit Button
                editButton =  new JButton(new ImageIcon(((new ImageIcon("images/button37.png")).getImage()).getScaledInstance(150, 35, java.awt.Image.SCALE_SMOOTH)));
				editButton.setContentAreaFilled(false);
				editButton.setBorder(null);
				editButton.setText("Edit");
				editButton.setForeground(Color.white);
				editButton.setFont(new Font("Lucida",Font.PLAIN,16));
				editButton.setHorizontalTextPosition(JButton.CENTER);
				editButton.setVerticalTextPosition(JButton.CENTER);
				editButton.setBounds(winWidth/3-75,70,150,35);  
		        rightside.add(editButton);
		        editButton.setVisible(false);
		        editButton.setCursor(new Cursor(Cursor.HAND_CURSOR));


                //    Delete Button


                deleteButton=new JButton(new ImageIcon(((new ImageIcon("images/button37.png")).getImage()).getScaledInstance(150, 35, java.awt.Image.SCALE_SMOOTH)));
		        deleteButton.setContentAreaFilled(false);
		        deleteButton.setBorder(null);
		        deleteButton.setText("Delete");
		        deleteButton.setForeground(Color.white);
		        deleteButton.setFont(new Font("Lucida",Font.PLAIN,16));
		        deleteButton.setHorizontalTextPosition(JButton.CENTER);
		        deleteButton.setVerticalTextPosition(JButton.CENTER);
		        deleteButton.setBounds(winWidth/2-75,70,150,35);  
		        rightside.add(deleteButton);
		        deleteButton.setVisible(false);	
		        deleteButton.setCursor(new Cursor(Cursor.HAND_CURSOR));

    

Here we are writing code for edit button functionality.

    
   
    editButton.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) {
				        addproductButton.setVisible(false);
				        cancleButton.setVisible(true);
				        updateButton.setVisible(true);
						productNametextField.setText(table.getValueAt(table.getSelectedRow(), 1).toString());
						productCategorytextField.setText(table.getValueAt(table.getSelectedRow(), 2).toString());
						productPriceTextfield.setText(table.getValueAt(table.getSelectedRow(), 3).toString());
						productQuantityTextField.setText(table.getValueAt(table.getSelectedRow(), 4).toString());
						productGstTextField.setText(table.getValueAt(table.getSelectedRow(), 5).toString());

					}
				});


    

Here we are writing code for delete button functionality.

    

    deleteButton.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) {
						
						boolean isSuccessdelete=deletedataFromTable(table.getValueAt(table.getSelectedRow(), 0).toString());
						if(isSuccessdelete){
					        JOptionPane.showMessageDialog(null, "Record deleted..."); 
							  displaylistToTable(table,getTableListData());


						}else{
					        JOptionPane.showMessageDialog(null, "Not deleted...");  

						}

					}

					
				});



    protected boolean deletedataFromTable(String string) {
         boolean issuccess=false;
         conn=SQLiteJDBCDriverConnection.connect1();
		 String sql = "delete from product where product_id= ?";

		 try {  
			 PreparedStatement stmt = conn.prepareStatement(sql);
			 stmt.setString( 1, string);
			 int action =stmt.executeUpdate();

		        if(action>0){
			    	   issuccess= true;
	 
			       }else{
			    	   issuccess= false;

			       }
		        stmt.close();  
		        conn.close();  
		    } catch (SQLException e) {  
		        JOptionPane.showMessageDialog(null, e);  
		    }  
		 
		 return issuccess;
		
	}




    

Create a "UPDATE" and "CANCEL" button UI it will appears when click on "EDITE" button.

    

            //    Update Button
            JButton updateButton = new JButton(new ImageIcon(((new ImageIcon("images/button37.png")).getImage()).getScaledInstance(200, 50, java.awt.Image.SCALE_SMOOTH)));
	        updateButton.setContentAreaFilled(false);
	        updateButton.setBorder(null);
	        updateButton.setText("Update");
	        updateButton.setForeground(Color.white);
	        updateButton.setFont(new Font("Lucida",Font.PLAIN,16));
	        updateButton.setHorizontalTextPosition(JButton.CENTER);
	        updateButton.setVerticalTextPosition(JButton.CENTER);
	        updateButton.setBounds(30,winHeight/2+ winHeight/9,200,50);  
	        updateButton.setVisible(false);
	        updateButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
	        ledtside.add(updateButton);

             
             //    Cancel Button
             JButton cancleButton = new JButton(new ImageIcon(((new ImageIcon("images/button37.png")).getImage()).getScaledInstance(200, 50, java.awt.Image.SCALE_SMOOTH)));
	        cancleButton.setContentAreaFilled(false);
	        cancleButton.setBorder(null);
	        cancleButton.setText("Cancle");
	        cancleButton.setForeground(Color.white);
	        cancleButton.setFont(new Font("Lucida",Font.PLAIN,16));
	        cancleButton.setHorizontalTextPosition(JButton.CENTER);
	        cancleButton.setVerticalTextPosition(JButton.CENTER);
	        cancleButton.setBounds(winWidth/3-200-30,winHeight/2+ winHeight/9,200,50);  
	        cancleButton.setVisible(false);        
	        cancleButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
	        ledtside.add(cancleButton);


    

Here we are writing code for update button functionality.

    
   
    updateButton.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					String productName="";
	            	String productCategory="";
	            	String productPriceString="";
	            	String productQuantity="";
	            	String productGstString="";

	               String var="";
          		   if(productNametextField.getText().isEmpty()){
          			   var=var+"Product Name shouldnot be Empty, ";
          			   
          		   }else{
          			 productName=productNametextField.getText().toString();
          		   }
          		   
          		 if(productCategorytextField.getText().isEmpty()){
        			   var=var+"Category shouldnot be Empty, ";
        			   
        		   }else{
        			   productCategory=productCategorytextField.getText().toString();
        		   }
          		if(productPriceTextfield.getText().isEmpty()){
     			   var=var+"Price shouldnot be Empty, ";
     			   
     		   }else{
     			  productPriceString=productPriceTextfield.getText().toString();
     		   }
          		if(productQuantityTextField.getText().isEmpty()){
      			   var=var+"quantity shouldnot be Empty ";
      			   
      		   }else{
      			 productQuantity=productQuantityTextField.getText().toString();
      		   }
          		if(productGstTextField.getText().isEmpty()){
       			   var=var+"Gst shouldnot be Empty ";
       			   
       		   }else{
       			 productGstString=productGstTextField.getText().toString();
       		   } 
          		    
          		   if(var==""){
            		     String generatedID=table.getValueAt(table.getSelectedRow(), 0).toString();      		  
          			 
	            		   
	            		  boolean isSussessFullEntered=updatetableIntryField(generatedID,productName,productCategory,productQuantity,productPriceString,productGstString);
	            		  if(isSussessFullEntered){
	            			  
	            			  productNametextField.setText("");
	            			  productCategorytextField.setText("");
	            			  productPriceTextfield.setText("");
	            			  productQuantityTextField.setText("");
	            			  productGstTextField.setText("");
	            			  displaylistToTable(table,getTableListData());
	               			 JOptionPane.showMessageDialog(frame, "Successfull Updated");
	            			  
	            		  }else{
		               			 JOptionPane.showMessageDialog(frame, "Not Update"); 
	            		  }
		   
          		   }else{
          			 JOptionPane.showMessageDialog(frame, var);

          		   }

				}
			});
	        



    protected boolean updatetableIntryField(String generatedID, String nameString, String categoryString,
		
         String countString, String priceString,String gst) {
		 Connection conn=SQLiteJDBCDriverConnection.connect1();
         boolean issuccess=false;
         Statement stmt = null;
         int action;		
      

	        PreparedStatement pst  = null;
	        try {
		             pst = conn.prepareStatement("UPDATE product SET product_name = ?, product_category = ?, product_count = ? , product_price = ?, product_gst = ?  WHERE product_id = ?"); 		            
		             pst.setString(1, nameString);
		             pst.setString(2, categoryString);
		             pst.setString(3, countString);
		             pst.setString(4, priceString);
		             pst.setString(5, gst);
		             pst.setString(6, generatedID);

		             action = pst.executeUpdate();
		             if(action>0){
				    	   issuccess= true;
		 
				       }else{
				    	   issuccess= false;

				       }
		           
	            } catch (Exception a) {
	                a.printStackTrace();
	            } finally {
	                if(rs != null){
	                     try{
	                          rs.close();
	                     } catch(Exception e){
	                         e.printStackTrace();
	                     }
	                }
	                if(pst != null){
	                    try{
	                        pst.close();
	                    } catch(Exception e){
	                        e.printStackTrace();
	                    }
	                }
	            }
	        
		return issuccess;
	}


    

Here we are writing code for cancel button functionality.

    
   
    cancleButton.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					
					    addproductButton.setVisible(true);
					    editButton.setVisible(false);
					    deleteButton.setVisible(false);
				        cancleButton.setVisible(false);
				        updateButton.setVisible(false);
				        productNametextField.setText("");
						productCategorytextField.setText("");
						productPriceTextfield.setText("");
						productQuantityTextField.setText("");
						productGstTextField.setText("");

				}

				
			});


    

At last we will manage closing of window

    
    private void exitForm(java.awt.event.WindowEvent evt) {                          
            //System.exit(0); which was used 
            // to fullfill your requirement you need to write below code
            frame.dispose();// here [this] keyword means your current frame
             //OR simply you can use this.setVisible(false); instead of this.dispose();
            previousFrame.setVisible(true); // this will displays your login frame
}

    panel.revalidate();
	panel.repaint();
         
	

Programmer Mirta is for learning and training. Projects might be simple to improve learning. Projects are constantly reviewed to avoid errors, but we cannot assure full correctness of all content. While using Programmer Mitra, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 2021 by Programmer Mitra. All Rights Reserved.