How to Split Image Into Multiple Pieces In Java

How to Create an Image Slicer In Java Netbeans

How to Split Image Into Multiple Pieces In Java


In this Java Tutorial we will see How To Slice an image into parts in java netbeans.
This program lets you upload an image and automatically splits it into a 4x4 (you can change it to more or less) grid of smaller images. Perfect for creating puzzles with image.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





How to Create an Image Slicer In Java Netbeans



Project Source Code:


package new_tutorials;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author 1BestCsharp
 */
public class ImageSlicer extends  JFrame{

    // Declare a panel to hold the grid of image slices
    private JPanel gridPanel;
     // Constants for window and image properties
    private static final int FRAME_WIDTH = 500;
    private static final int FRAME_HEIGHT = 500;
    // Target size for resizing the image
    private static final int IMAGE_SIZE = 400;
    // 4x4 grid (16 image slices in total)
    private static final int GRID_SIZE = 5; 
    
    public ImageSlicer(){
        // Set up the main window properties
        setTitle("Image Splitter");
        setSize(FRAME_WIDTH, FRAME_HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        setLocationRelativeTo(null);
        
        // Create the "Upload and Split Image" button
        JButton uploadButton = new JButton("Upload and Split Image");
        uploadButton.setFocusPainted(false);
        uploadButton.setBackground(new Color(33,150,243));
        uploadButton.setForeground(Color.WHITE);
        uploadButton.setBorder( BorderFactory.createEmptyBorder(10,20,10,20));
        uploadButton.setFont(new Font("Arial", Font.PLAIN, 17));
        uploadButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        // Create a panel to hold the grid of image slices (initially empty)
        // Use GridLayout to divide the panel into a 4x4 grid, no gaps between cells
        gridPanel = new JPanel(new GridLayout(GRID_SIZE, GRID_SIZE, 0, 0));
        gridPanel.setBackground(Color.WHITE);
        
        // Add the grid panel inside a scroll pane in case the content exceeds the window size
        JScrollPane scrollPane = new JScrollPane(gridPanel);
        scrollPane.setPreferredSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
        
        // Add an action listener to the button (what happens when it's clicked)
        uploadButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileFilter(new FileNameExtensionFilter("Images Files", ImageIO.getReaderFileSuffixes()));
                int returnValue = fileChooser.showOpenDialog(null);
                if(returnValue == JFileChooser.APPROVE_OPTION){
                    try {
                        File selectedFile = fileChooser.getSelectedFile();
                        BufferedImage image = ImageIO.read(selectedFile);
                        // Resize the image to the specified size (400x400 pixels)
                        BufferedImage reseizedImage = resizeImage(image, IMAGE_SIZE, IMAGE_SIZE);
                         // Split the resized image into 16 (4x4) slices and display them
                        splitAndDisplay(reseizedImage);
                    } catch (IOException ex) {
                        Logger.getLogger(ImageSlicer.class.getName()).log(Level.SEVERE, null, ex);
                    }   
                }
            }
        });
        
        JPanel panel = new JPanel();
        panel.setBackground(Color.WHITE);
        panel.add(uploadButton);
        
        add(panel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
    }
    
            
         // Function to resize the image to the target width and height
         private BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight){
             Image resizedImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
             BufferedImage bufferedResizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
             Graphics2D g2d = bufferedResizedImage.createGraphics();
             g2d.drawImage(resizedImage, 0, 0, null);
             g2d.dispose();
             return bufferedResizedImage;
         }
        
         
         // Function to split the image into slices and display them in the grid
         private void splitAndDisplay(BufferedImage image){
             int sliceWidth = image.getWidth() / GRID_SIZE;
             int sliceHeight = image.getHeight() / GRID_SIZE;
             
             gridPanel.removeAll();
             
             for(int y = 0; y < GRID_SIZE; y++){
                 for(int x = 0; x < GRID_SIZE; x++){
                     BufferedImage slice = image.getSubimage(x*sliceWidth, y*sliceHeight, sliceWidth, sliceHeight);
                     
                     ImageIcon imageIcon = new ImageIcon(slice);
                     JLabel sliceLabel = new JLabel(imageIcon);
                     sliceLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY,1));
                     gridPanel.add(sliceLabel);
                 }
             }
             
             gridPanel.revalidate();
             gridPanel.repaint();
             
         }
         
    
    public static void main(String[] args) {
        new ImageSlicer().setVisible(true);
    }
}

    


The Final Result:

Split Image Into Parts In Java

Slice Image Into Parts In Java Swing








Java Cafe Shop Management System Source Code

Cafe Shop Management System Project Using Java And MySQL Database


Java Cafe Shop Management System Source Code


This coffee shop management system project is built in java programming language and mysql database providing a user-friendly interface for managing different aspects of a coffee shop operations.

This project requires few technologies:
- Java (built in NetBeans 8.2) for the core application.
MySQL with phpMyAdmin for database management.
- XAMPP server for local hosting.
- Free Images from Pixabay.

Watch This Full Demo


1 - The Login Form

The login form provides secure access to the Cafe Shop System Dashboard. 
Users must enter their Email and password to authenticate their credentials.
The interface features a modern dark theme with a custom window design that users can freely drag and reposition. 
An animated coffee cup at the top adds a unique visual element that reflects the cafe's identity.
The form includes modern input fields with clear placeholder text to guide users. 
Built-in form validation and error handling ensure data accuracy and provide helpful feedback if incorrect information is entered.



Java Cafe Shop - Login Form

Java Cafe Shop - Login Form Error

2 - The Coffee Shop Dashboard Form

After the user successfully login, he will see this application dashboard.
The dashboard follows a modern, coffee-inspired color scheme with warm browns and beiges that really give it that cozy cafĂ© feel. 

Java Cafe Shop - Dashboard Form

Java Cafe Shop - Dashboard Form 2


The interface is split into two main sections:
The Sidebar:
- A collapsible navigation menu that can be expanded or shrunk with a smooth animation.

Java Cafe Shop - Collapsing Menu


- Features the BrewBean logo at the top.
- Contains easy-to-spot menu items with icons for Dashboard, Menu, Customers, Orders, and Users (admin-only).
- Each menu item has a subtle hover effect and clear visual feedback when selected.
if the user type is "Admin" he will see the "Users" tab to manage users.

The Main Content Area:
- Clean white background with a professional header showing a 'Dashboard' title, you can change it with The current section title or current date/time, A welcome message with the logged-in user's name A neat circular avatar showing the user's initial.
This header will be visible in all the system panels.


- When you click on the avatar icon a menu show up, showing the logged in user name and email and 2 menu items allowing the user to view his profile or to logout of the system .
If you click on 'My Profile' a form will show up listing the user info.






The dashboard is divided into three main sections:
1. Summary Cards
Four clean, white cards showing the most important metrics at a glance: Total Sales (in dollars), Number of Orders, Total Customers and Average Order Value.


2. Visual Analytics
Two side-by-side charts with a cool hover effect: 
A - Orders Status: Shows the distribution of order statuses (Completed, In Progress, Pending, etc.) 
B - Popular Items: Visualizes the most-ordered items in the café




3. Recent Orders Table
A beautiful modern table showing the last 10 orders.




3 - Coffee Shop Menu Panel

- It's a modern, visually appealing panel that displays the coffee shop menu items in a grid layout with some really cool features.
- The Menu items are arranged in a 3-column grid Each item card has a nice rounded corner design, There's smooth scrolling when you have lots of items.
- Each card is like a little showcase for a menu item it contains : 
A -  A main image area for the item photo. 
B - Item name in bold.
C - Description in a lighter font.
D - Price tag with a subtle colored background. 
E - Edit and delete buttons that appear as icons.
F - Cool hover effects with animated borders.




- Add A New Menu Item To The Coffee Shop:
The "Add" Button Sits in the top-right corner Clear "+ " symbol Opens a dialog to add new items.






- Card Actions
Each menu card has an edit and delete buttons.
A - Edit button opens a dialog to modify the item.






B - Delete button shows a detailed confirmation message. 




4 - The Customers Form

This is a beautifully designed customer management interface for the cafĂ©, with several sections. 
Let me break it down: 
- Header.
At the top, you'll see "CafĂ© Clients" written, along with a handy "+" button to add new customers. 
It's like having a digital guest book for your café!




- If you click on the '+' button at the top A modern dialog window that makes adding and editing customer information easy will show up.




- Smart Search and Filtering
The system includes a modern search bar where you can quickly find any customer by typing their name, email, or phone number. 
Next to it, there's a dropdown menu that lets you filter customers based on their order history:
- No Orders (newcomers).
- 1-2 Orders (occasional visitors).
- 3-5 Orders (regular customers).
- 6-10 Orders (frequent visitors).
- 11-20 Orders (loyal customers).
- 20+ Orders (VIP customers).



The Customer Table is beautifully designed showing all your customer information. Each row displays the customer loyalty at a glance:
* Gray for new customers with no orders. 

* Light blue for customers with 1-2 orders. 

* Light green for the 3-5 order range. 

* Light yellow for 6-10 orders. 

* Light orange for 11-20 orders.

* Light purple with a star for VIP customers with 20+ orders.


Each customer entry comes with two buttons:
- A blue "Edit" button with a pen icon for updating customer information.



- A red "Remove" button with a trash icon for removing customers (with a safety confirmation, of course!)



- Smart Pagination.
To keep things organized, the interface shows 5 customers at a time, with easy-to-use navigation buttons to move between pages.


- The Chart Panel.
A visual representation of customer spending patterns helps you understand your business better.



- The Customers Stats
Three beautifully designed cards show your key metrics: Total number of customers, Average revenue per customer, Average customers per day.
Each stat card comes with its own color scheme and icon, making it easy to quickly understand your café's performance.


5 - The Orders Form

This form is responsible for managing and keeping track of orders.


At the top of the panel, you'll see the "CafĂ© Ordres" title, along with a "+" button for adding new orders. 


Let's break down its features and see what makes it special.

- Customer Selection.
Making It Simple The customer selection section is simple. Instead of overwhelming users with a massive dropdown list, when search button is clicked, it opens a separate customer selection dialog.
This approach makes finding and selecting customers much more manageable than scrolling through an endless list.




now the customer has been selected.


- The Heart of the Form
The items table is where the magic happens. It's packed with smart features that make order entry a easy.

Smart Item Selection
The coolest part is the autocomplete feature for items. As you type, it shows suggestions in a sleek popup window.



Easy Quantity Management
A dedicated column for quantities with automatic validation Only accepts numbers (no accidental letter typing!) Defaults to 1 if you enter something invalid

Dynamic Calculations 
The form is constantly working to keep your totals accurate: 
Prices update automatically when you select an item 
Totals calculate instantly when you change quantities 
The overall order total updates in real-time


Smooth Delete Function
Removing items is very easy: 
Each row has a subtle delete button. 
Items fade out smoothly when deleted 
The total updates automatically after deletion

Status and Totals 
Keeping Track At the bottom of the form, you'll find: 
- A clear display of the order total in a read-only field. 
- A modern dropdown for selecting order status (Pending, Processing, Completed, or Cancelled).
The total updates automatically as you add or modify items.


The Action Buttons  
- A large, clearly visible "Add Order" button. 
- A similarly sized "Cancel" button. 
- Both buttons have hover effects and are sized perfectly for easy clicking.





Now the order has been addedd and the orders panel shows you everything you need to know about each order [ Order ID, Customer name, Items ordered, Total amount, Current status, Date, Action buttons ].


Each row has three action buttons:
- A blue "Edit" button for modifying only orders status.
The status column uses different colors to instantly show you where each order stands:
* Yellow for pending orders. 
* Blue for processing orders. 
* Green for completed orders. 
* Red for cancelled orders.




- A red "Remove" button for deleting orders.




- A gray "View" button for seeing all the details. 
Instead of the typical boxy Swing window, we have a floating card with smooth rounded corners and a subtle shadow effect.

* The Header Section is where you'll find the order number displayed  accompanied by the order date right below it.
* The Order Items Section is where each order item is displayed in its own mini-card with the item image, name, quantity, price and a calculated subtotal.
If you have many items, the list scrolls smoothly with a modern-styled scrollbar that appears only when needed.
* The Footer Section The footer is separated by a thin line and contains two key elements: A stylish total amount display with a gradient background Two action buttons: "Print Order" and "Close".

Print Functionality: When you click the print button, you get a professionally formatted receipt with: 
* A clean header with the company name. 
* Detailed item listing with quantities and prices. 
* Tax calculations. 
* A friendly thank-you message at the bottom. 
* All perfectly aligned and styled for paper






Smart Search and Filtering
Above the table, there's a search bar where you can quickly find specific orders. Type in a customer name, order ID, or even item names, and the table updates instantly. Next to it, there's a dropdown menu that lets you filter orders by status.











The Chart Panel 
On the left, there's a visual chart showing the distribution of order statuses. It's a great way to get a quick overview of how many orders are pending, processing, completed, or cancelled.


The Stats Cards
On the right, you'll find three beautifully designed cards showing key metrics: Total number of orders, Total revenue, Average order value.
Each card has its own color scheme and icon, making the information both attractive and easy to digest.


8 - The User Panel

This is a simple interface to manage users only visible to admins.
like the other panels the header section has a modern "+" button for adding new users.


The Main Table: The user management table has several modern features:

Smart Password Handling
The password column is particularly clever. Instead of just showing dots, it includes:
* A custom password field that masks the content.
* A beautifully designed eye icon toggle button.
* The ability to show/hide passwords individually per row.


Action Buttons 
Each row has two action buttons with custom icons (pen for edit, trash for delete):

- An "Edit" button in a pleasant blue shade.





A "Remove" button in a careful red tone Both buttons feature:





if you want the source code of this Coffee Shop click on the download button below






Delivery: Instant Source Code Download.
Disclaimer: This source code is an educational resource. Users are responsible for implementation and troubleshooting.