Affichage des articles dont le libellé est Navigation buttons. Afficher tous les articles
Affichage des articles dont le libellé est 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





Paginated Table Using Tkinter In Python

How To Create a Paginated Table Using Tkinter In Python

Paginated Table Using Tkinter In Python


In this Python tutorial we will create a paginated table using the Tkinter library for the graphical user interface. 
The table shows a list of data and includes pagination controls with "Previous" and "Next" buttons. 
These buttons allow you to navigate through different pages of data, updating the rows displayed according to the current page.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for GUI.
- VS Code Editor.




Project Source Code:




import tkinter as tk
from tkinter import ttk

class TablePaginationFrame(tk.Tk):
def __init__(self):
super().__init__()
self.title("Paginated Table")
self.geometry("400x300")
self.create_ui()

def create_ui(self):
ttk.Style().configure("TButton", padding=5, relief="flat")

# Create a Treeview widget for displaying the table
self.table_model = ttk.Treeview(self, columns=("ID", "Name"),
        show="headings", height=5)
self.table_model.heading("ID", text="ID")
self.table_model.heading("Name", text="Name")
self.table_model.column("ID", width="50")
self.table_model.column("Name", width="50")
self.table_model.tag_configure("oddrow", background="#f0f0f0")

# Create a vertical scrollbar for the table
scroll_y = ttk.Scrollbar(self, orient="vertical",
        command=self.table_model.yview)
self.table_model.configure(yscroll=scroll_y.set)

# Create Previous and Next buttons for pagination
self.prev_button = ttk.Button(self, text="Previous", command=self.prev_page)
self.next_button = ttk.Button(self, text="Next", command=self.next_page)

# Grid layout for widgets
self.table_model.grid(row = 0, column = 0, columnspan = 2, padx = 0,
        pady = 5, sticky = "nsew")
scroll_y.grid(row = 0, column = 2, sticky="nsew")
self.prev_button.grid(row=1, column=0, padx=5, pady=5, sticky="w")
self.next_button.grid(row=1, column=1, padx=5, pady=5, sticky="e")

# Configure grid weights to make the table expandable
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)

# Initialize pagination parameters
self.current_page = 1
self.items_per_page = 10
self.update_table_model()


def prev_page(self):
# Go to the previous page if available
if self.current_page > 1:
self.current_page -= 1
self.update_table_model()

def next_page(self):
# Go to the next page if available
if self.current_page < self.get_total_pages():
self.current_page += 1
self.update_table_model()


def update_table_model(self):
# Clear the current table contents
self.table_model.delete(*self.table_model.get_children())

# Calculate the indices for the start and end of the current page
start_index = (self.current_page - 1) * self.items_per_page
end_index = min(start_index + self.items_per_page, len(self.get_data()))

# Iterate over the data for the current page
for i in range(start_index, end_index):
# Get the values for the current row
values = self.get_data()[i]
# Determine tags for the row to set alternate row background colors
tags = ("oddrow") if i % 2 != 0 else ()
# Insert the row into the table with the calculated values and tags
self.table_model.insert("", "end", values = values, tags=tags)
# Disable/enable pagination buttons based on current page
self.prev_button["state"] = tk.NORMAL if self.current_page > 1
        else tk.DISABLED
self.next_button["state"] = tk.NORMAL
        if self.current_page < self.get_total_pages() else tk.DISABLED

def get_total_pages(self):
# Calculate total pages based on data length and items per page
return -(-len(self.get_data()) / self.items_per_page)


def get_data(self):
# Mock data for the table
return [
(1, "Apple"), (2, "Banana"), (3, "Orange"), (4, "Grapes"),
                (5, "Strawberry"),
(6, "Watermelon"), (7, "Pineapple"), (8, "Mango"), (9, "Peach"),
                (10, "Kiwi"),
(11, "Blueberry"), (12, "Cherry"), (13, "Raspberry"), (14, "Pear"),
                (15, "Plum"),
(16, "Avocado"), (17, "Coconut"), (18, "Lemon"), (19, "Pomegranate"),
                (20, "Papaya"),
(21, "Apricot"), (22, "Blackberry"), (23, "Cantaloupe"),
                (24, "Cranberry"), (25, "Fig"),
(26, "Guava"), (27, "Lychee"), (28, "Mango"), (29, "Passion Fruit"),
                (30, "Tangerine"),
(31, "Dragon Fruit"), (32, "Kumquat"), (33, "Lime"),
                (34, "Nectarine"), (35, "Persimmon"),
(36, "Rambutan"), (37, "Starfruit"), (38, "Ugli Fruit"),
                (39, "Honeydew Melon"), (40, "Jackfruit"),
(41, "Lingonberry"), (42, "Mangosteen"), (43, "Olive"),
                (44, "Quince"), (45, "Soursop"),
(46, "Tamarillo"), (47, "Ugni"), (48, "Yangmei"), (49, "Zucchini"),
                (50, "Elderberry")
]



if __name__ == "__main__":
app = TablePaginationFrame()
app.mainloop()



The Final Result:

How to Create a Table with Pagination Buttons in Python Tkinter









VB.NET SQL SERVER Data Navigation

VB.NET - How To Create SQLServer Records Navigation Using Visual Basic.Net

                                                                                                                         

In This VB.NET Tutorial We Will See How To Create Navigation Buttons  ( First, Next, Previous, Last ) With Microsoft SQL DataBase Values Using Visual Basic .NET Programming Language.


Project Source Code:

Imports System.Data.SqlClient

Public Class VBNET_SQL_Navigation

    Dim connection As New SqlConnection("Server= SAMSNG-PC; Database = TestDB; Integrated Security = true")
    Dim index As Integer = 0
    Dim table As New DataTable()


    Private Sub VBNET_SQL_Navigation_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        showData(index)

    End Sub

    Public Sub showData(position As Integer)

        Dim command As New SqlCommand("select * from Users", connection)
        Dim adapter As New SqlDataAdapter(command)

        adapter.Fill(table)

        TextBoxID.Text = table.Rows(position)(0).ToString()
        TextBoxFN.Text = table.Rows(position)(1).ToString()
        TextBoxLN.Text = table.Rows(position)(2).ToString()
        TextBoxAGE.Text = table.Rows(position)(3).ToString()

    End Sub


    Private Sub BTN_FIRST_Click(sender As Object, e As EventArgs) Handles BTN_FIRST.Click

        index = 0
        showData(index)

    End Sub

    Private Sub BTN_NEXT_Click(sender As Object, e As EventArgs) Handles BTN_NEXT.Click

        index += 1
        If index > table.Rows.Count() - 1 Then

            index = table.Rows.Count() - 1

        End If
        showData(index)

    End Sub

    Private Sub BTN_PREVIOUS_Click(sender As Object, e As EventArgs) Handles BTN_PREVIOUS.Click

        index -= 1
        If index < 0 Then
            index = 0
        End If
        showData(index)

    End Sub

    Private Sub BTN_LAST_Click(sender As Object, e As EventArgs) Handles BTN_LAST.Click

        index = table.Rows.Count() - 1
        showData(index)

    End Sub
End Class

///////////////OUTPUT:

vb.net sql data navigation