Affichage des articles dont le libellé est code for navigation buttons. Afficher tous les articles
Affichage des articles dont le libellé est code for navigation buttons. Afficher tous les articles

Java - Add Pagination to JTable

How to Create a Paginated JTable In Java Netbeans


In this Java Tutorial we will see How To Create a paginated JTable with sample data, allowing the user to navigate through different pages using "Previous" and "Next" buttons In Java Using Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:



package new_tutorials;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;

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

    private DefaultTableModel tableModel;
    private JTable table;
    private JButton prevButton;
    private JButton nextButton;
    private int currentPage = 1;
    private final int itemsPerPage = 5;
    
    public TablePaginationFrame()
    {
        setTitle("Paginated Table");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400,300);
        setLocationRelativeTo(null);
        intializeUI();
    }
    
    private void intializeUI(){
     
        UIManager.put("Button.focus", new Color(0,0,0,0));
        UIManager.put("Button.select", new Color(200,200,200));
        UIManager.put("Button.background", new Color(240,240,240));
        UIManager.put("Button.border", BorderFactory.createEmptyBorder(5, 15, 5, 15));
        
        tableModel = new DefaultTableModel(new Object[]{"ID","Name"}, 0);
        table = new JTable(tableModel);
        table.setRowHeight(25);
        table.setFont(new Font("Arial", Font.PLAIN, 18));
        JScrollPane scrollPane = new JScrollPane(table);
        
        prevButton = new JButton("Previous");
        nextButton = new JButton("Next");
        
        prevButton.addActionListener((e) -> {
            if(currentPage > 1){
                currentPage--;
                updateTableModel();
            }
        });
        
        nextButton.addActionListener((e) -> {
            if(currentPage < getTotalPages()){
                currentPage++;
                updateTableModel();
            }
        });
        
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(prevButton);
        buttonPanel.add(nextButton);
        
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
        
        updateTableModel();
    }
    
    
    private void updateTableModel(){
        
        // Calculate the start and end indices for the current page
        int startIndex = (currentPage - 1) * itemsPerPage;
        int endIndex = Math.min(startIndex + itemsPerPage, getData().length);
        
        // Clear the existing table model and add rows for the current page
        tableModel.setRowCount(0);
        for(int i = startIndex; i < endIndex; i++){
            tableModel.addRow(getData()[i]);
        }
        
        // Enable/disable pagination buttons based on the current page
        prevButton.setEnabled(currentPage > 1);
        nextButton.setEnabled(currentPage < getTotalPages());
        
    }
    
    
    private int getTotalPages(){
        // Calculate the total number of pages based on 
        // the total data length and items per page
        return (int) Math.ceil((double)getData().length / itemsPerPage);
        
    }
    
    private Object[][] getData(){
        // Sample data for the table
        return new Object[][]{ 
                {1, "Item 1"},
                {2, "Item 2"},
                {3, "Item 3"},
                {4, "Item 4"},
                {5, "Item 5"},
                {6, "Item 6"},
                {7, "Item 7"},
                {8, "Item 8"},
                {9, "Item 9"},
                {10, "Item 10"},
                {11, "Item 11"},
                {12, "Item 12"},
                {13, "Item 13"},
                {14, "Item 14"},
                {15, "Item 15"},
                {16, "Item 16"},
                {17, "Item 17"},
                {18, "Item 18"},
                {19, "Item 19"},
                {20, "Item 20"},
                {21, "Item 21"},
                {22, "Item 22"},
                {23, "Item 23"},
                {24, "Item 24"},
                {25, "Item 25"},
                {26, "Item 26"},
                {27, "Item 27"},
                {28, "Item 28"},
                {29, "Item 29"},
                {30, "Item 30"},
                {99, "shdchsdbs shdsc"},
                {777, "euebvdi vdbcq"}
        };
    }
    
    
    public static void main(String[] args) {
        TablePaginationFrame frame = new TablePaginationFrame();
        frame.setVisible(true);
    }
    
}




The Final Result:

Java Jtable Pagination Buttons

Jtable Pagination Buttons In Java Netbeans

Jtable Pagination Buttons In Java Swing





Database Data Navigation in PHP

How to Navigate and Display Database Records Using PHP

How to Navigate and Display Database Records Using PHP


In this PHP tutorial, we will see how to to retrieve product information from a database and display it within an HTML form. 
Users can navigate through the products by using navigation buttons, and the form fields will dynamically update to show the details of the selected product.



Project Source Code:



<?php

// Connect to the database
require_once "db_connect.php";

// Define the SQL query to select all products from the "product" table
$query = "SELECT * FROM `product`";

// Prepare the SQL statement
$stmt = $conn -> prepare($query);

// Execute the SQL statement
$stmt->execute();

// Fetch all the results from the statement and store them in an array
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Initialize an empty array to store the products
$products = array();

foreach( $results as $row ){
$product = array("id"=>$row["id"],
"name"=>$row["name"],
"price"=>$row["price"],
"image"=>$row["image"]
);

// Add the product array to the products array
array_push($products, $product);
}


?>

<!DOCTYPE html>
<html>
<head>
<title>Data Navigation</title>
<style>

body{ font-family:Arial, sans-serif; background-color:#f2f2f2; }

form{ background-color:#fff; padding:20px; width:500px; margin: 25px auto;
border-radius:5px; box-shadow: 0 0 10px rgba(0,0,0,0.2); }
h1{ text-align:center; color:#333; margin-bottom:20px; }

.form-row{ margin:10px 0; }

input{ padding:10px; margin:10px 0; border:1px solid #ccc;
border-radius:4px; box-sizing:border-box; width:100%; }

button{ background-color:#4caf50; color:#fff; padding:10px 20px; border:none;
border-radius:4px; cursor:pointer; margin-top:10px; width:24%;
font-size:16px; }

button:hover{ background-color:#45a049; }

#image{ display:flex; align-items:flex-start; }

#image label{ margin-right:10px; }

#image img{ margin:10px; width:50%; height:150px; border-radius:5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.3); }

</style>
</head>
<body>

<form id="product-form">
<h1>Product Information</h1>
<div class="form-row">
<label for="product-id">ID:</label>
<input type="text" id="product-id" name="product-id">
</div>
<div class="form-row">
<label for="product-name">Name:</label>
<input type="text" id="product-name" name="product-name">
</div>
<div class="form-row">
<label for="product-price">Price:</label>
<input type="text" id="product-price" name="product-price">
</div>
<div class="form-row">
<div id="image">
<label for="product-image">Image:</label>
<img id="product-image" src="">
</div>
</div>
<div class="form-row">
<button type="button" id="btn-first">First</button>
<button type="button" id="btn-prev">Previous</button>
<button type="button" id="btn-next">Next</button>
<button type="button" id="btn-last">Last</button>
</div>

<script>

// convert the PHP array to a JavaScript object in JSON format.
const products = <?php echo json_encode($products); ?>

// Get the buttons
const btnFirst = document.getElementById('btn-first');
const btnNext = document.getElementById('btn-next');
const btnPrevious = document.getElementById('btn-prev');
const btnLast = document.getElementById('btn-last');

// Define a variable to keep track of the current index
let currentIndex = 0;

// Function to update the form fields based on the current index
function updateForm(){

const product = products[currentIndex];

document.getElementById('product-id').value = product.id;
document.getElementById('product-name').value = product.name;
document.getElementById('product-price').value = product.price;
document.getElementById('product-image').src = product.image;

}

// Function to handle button clicks
function handleButtonClick(e)
{
switch(e.target.id){
case 'btn-first':
currentIndex = 0;
break;
case 'btn-prev':
currentIndex = Math.max( currentIndex - 1, 0 );
break;
case 'btn-next':
currentIndex = Math.min( currentIndex + 1, products.length - 1 );
break;
case 'btn-last':
currentIndex = products.length - 1;
break;
default:
break;
}

updateForm();

}

// Add event listeners to the buttons
btnFirst.addEventListener('click', handleButtonClick);
btnNext.addEventListener('click', handleButtonClick);
btnPrevious.addEventListener('click', handleButtonClick);
btnLast.addEventListener('click', handleButtonClick);

// Initialize the form
updateForm();


</script>


</body>
</html>



Code Explanation:

PHP Section: This PHP code connects to a database using "db_connect.php," defines and executes an SQL query to select all products from a "product" table, fetches and stores the results in an array, and constructs an array of product information.

HTML/JavaScript Section: This code generates an HTML form with fields for product information.
It includes navigation buttons (First, Previous, Next, Last) to move between products and applies CSS styles.
JavaScript manages button clicks, updates form fields with product data, and keeps track of the current product.
listeners are added for button interaction, and the form is initialized through the updateForm function.



OUTPUT:


Database Data Navigation in PHP

Data Navigation in PHP




if you want the source code click on the download button below










Java - Images Gallery Project In Netbeans

How to Create Image Gallery in Java NetBeans

How to Create Image Gallery in Java NetBeans


In this Java Long Tutorial we will see how How To Create an images gallery application using Java Swing in Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:

- Loaded Images from a specified directory (in this code, "C:\images"), and add the supported image files (with extensions such as jpg, jpeg, png, and gif) to the list of images.
- Displayed the selected image in in the image view.
- Navigate through the images using the "Previous" and "Next" buttons.
- Search for specific images by entering a search term in the text field, which filters the list to display matching image names.




Project Source Code:


package imagesgalleryapp;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 *
 * @author 1BestCsharp
 */

public class ImagesGalleryApp extends JFrame {

    private DefaultListModel<ImageInfo> imageListModel;
    private JList<ImageInfo> imageList;
    private JLabel imageView;
    private JButton prevButton;
    private JButton nextButton;
    private JTextField searchField;
    private List<ImageInfo> images;
    
    public ImagesGalleryApp(){
        try
        {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        
        setTitle("Image Gallery");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800,600);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());
        images = new ArrayList<>();
        imageListModel = new DefaultListModel<>();
        initialize(); // initialize the user interface
        
    }
    
    // create a method to initialize the user interface
    private void initialize()
    {
        // Create a list to display image names
        imageList = new JList<>(imageListModel);
        imageList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        imageList.addListSelectionListener(e->displaySelectedImage());
        
        // Display selected image
        imageView = new JLabel();
        imageView.setHorizontalAlignment(JLabel.CENTER);
        
        // Previous & Next buttons to navigate images
        prevButton = new JButton("Previous");
        prevButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
                navigateImage(-1);
                
            }
        });
        
        nextButton = new JButton("Next");
        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
                navigateImage(1);
                
            }
        });
        
        // Search field to filter images by name
        searchField = new JTextField(20);
        searchField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
             
                searchImage(searchField.getText());
                
            }
        });
        
        // Create top panel containing search field
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        topPanel.add(new JLabel("Search"));
        topPanel.add(searchField);
        
        // Create center panel with list and image view
        JPanel centerPanel = new JPanel(new GridLayout(1, 2));
        centerPanel.add(new JScrollPane(imageList));
        centerPanel.add(imageView);
        
        // Create bottom panel with navigation buttons
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        bottomPanel.add(prevButton);
        bottomPanel.add(nextButton);
        
        // Add panels to the main frame
        add(topPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);
        
    }
    
    
    
    
    // Create Class to store image information
    private class ImageInfo{
        
        private String filePath;
        private String name;
        
        public ImageInfo(String filePath, String name)
        {
            this.filePath = filePath;
            this.name = name;
        }
        
        @Override
        public String toString(){ return name; }
        
    }
    
    
    // Create a Function to Navigate through images
    private void navigateImage(int offset)
    {
        int selectedIndex = imageList.getSelectedIndex();
        if(selectedIndex >= 0)
        {
            int newIndex = (selectedIndex + offset + images.size()) % images.size();
            imageList.setSelectedIndex(newIndex);
            displaySelectedImage();
        }
    }
    
    
    
    
    
    // Create a Function to Search images based on the provided search term
    private void searchImage(String searchTerm)
    {
        imageListModel.clear();
        for(ImageInfo image : images)
        {
            if(image.name.toLowerCase().contains(searchTerm.toLowerCase()))
            {
                imageListModel.addElement(image);
            }
        }
        displaySelectedImage();
    }
    
    
    
    // Create a Function to Display selected image in the image view
    public void displaySelectedImage()
    {
        ImageInfo selectedImage = imageList.getSelectedValue();
        if(selectedImage != null)
        {
            ImageIcon imageIcon = new ImageIcon(selectedImage.filePath);
            Image scaledImage = imageIcon.getImage().getScaledInstance(imageView.getWidth(), imageView.getHeight(), Image.SCALE_SMOOTH);
            imageView.setIcon(new ImageIcon(scaledImage));
        }
    }
    
    

    // Create a Function to Load images from a specified directory
    private void loadImagesFromDirectory(String directoryPath)
    {
        File directory = new File(directoryPath);
        if(directory.isDirectory())
        {
            File[] imageFiles = directory.listFiles( 
                    file->file.isFile() && isSupported(file.getName()) );
            if(imageFiles != null)
            {
                for(File imageFile: imageFiles)
                {
                    images.add(new ImageInfo(imageFile.getAbsolutePath(), imageFile.getName()));
                    imageListModel.addElement(new ImageInfo(imageFile.getAbsolutePath(), imageFile.getName()));
                }
            }
        }
    }
    
    // Create a Function to Check if a file has a supported image extension
    private boolean isSupported(String fileName)
    {
        String[] supportedExtensions = {"jpg","jpeg","png","gif"};
        String extension = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        
        for(String ext : supportedExtensions)
        {
            if(extension.equals(ext))
            {
                return true;
            }
        }
        
        return false;
    }
    
    
    
    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(()->{
        
            ImagesGalleryApp app = new ImagesGalleryApp();
            app.loadImagesFromDirectory("C:\\images");
            app.setVisible(true);
            
        });
        
        
    }

}




The Final Result:



Java Image Gallery 1

Java Image Gallery 2

Java Image Gallery 3

Java Image Gallery 4





if you want to download the project files click on the button below

download the source code