Java Text Animation

How to Create a Text Animation Effects in Java Netbeans

How to Create a Text Animation Effects in Java Netbeans


In this Java Tutorial we will see How To Create a text animations with growing text, gradient colors and shadow effects In Java Using Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:



/**
 *
 * @author 1BestCsharp
 */

public class TextAnimation extends JFrame{

        private ModernTextEffect textEffect;
        
        /**
        * Constructor: Sets up the main application window and animation components
        */
        public TextAnimation(){
            
                setTitle("Text Animation Effect");
                setSize(1200, 600);
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setLocationRelativeTo(null);
                
                // Create text effect component with the message to display
                textEffect = new ModernTextEffect("FIGHT!");
                add(textEffect);
                
                // Set up animation timer
                Timer timer = new Timer(16, e -> textEffect.animate());
                timer.start();
            
        }

        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> {
                new TextAnimation().setVisible(true);
            });
    }
    
}

/**
 * Custom JPanel that handles the text animation effect
 */
class ModernTextEffect extends JPanel{
    
    private String text;              // Text to display
    private float scale = 0.1f;       // Current scale of the text (for zoom effect)
    private boolean growing = true;   // Whether text is currently growing in size
    private float angle = 0;          // Animation angle for movement effects
    private float time = 0;           // Time accumulator for color animations
    
    // Gradient colors for the effect
    private Color[] gradientColors = {
        new Color(255, 0, 128),  // Pink
        new Color(255, 102, 0),  // Orange
        new Color(255, 215, 0),  // Gold
        new Color(0, 255, 255)   // Cyan
    };
    
    
     /**
     * Constructor: Initializes the text effect with the provided message
     * 
     * @param text The text to animate
     */
     public ModernTextEffect(String text) {
        this.text = text;
        setBackground(new Color(20, 20, 25)); // Dark background
    }
    
     /**
     * Advances the animation by one frame
     * Called by the timer in the main class
     */
     public void animate() {
         
            // Handle the initial "grow" animation
            if (growing) {
               scale += 0.05f;
               if (scale >= 1.0f) {
                   growing = false;
                   scale = 1.0f;
               }
           }
            
            // Update animation parameters
            angle += 0.05f;
            time += 0.1f;
            
           // Trigger repaint to show the next animation frame
           repaint();
        
         
     }
    
     
     /**
     * Renders the text with special effects
     */
    @Override
    protected void paintComponent(Graphics g) {
        
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            
            // Enable high quality rendering
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                    RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            
            // Reset composite in case it was modified previously
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
            
            // Calculate text position (centered)
            Font baseFont = new Font("Impact", Font.BOLD, 150);
            FontMetrics metrics = g2d.getFontMetrics(baseFont);
            int textWidth = metrics.stringWidth(text);
            int x = (getWidth() - textWidth) / 2;
            int y = (getHeight() + metrics.getHeight()) / 2;
            
            // Set up transform for positioning and scaling
            AffineTransform transform = new AffineTransform();
            transform.translate(x, y);
            transform.scale(scale, scale);
            
            // Add subtle rotation after initial growth animation completes
            if (!growing) {
                transform.rotate(Math.sin(angle) * 0.05, textWidth / 2, 0);
            }
            
            Font scaledFont = baseFont.deriveFont(transform);
            
            // Draw shadow/glow layers
            // More layers (higher i) = farther back in the shadow stack
            for (int i = 20; i > 0; i--) {
                
                  float progress = (float) i / 20.0f;
                  Color color = getGradientColor(progress + (time * 0.1f));
                  
                 // Make shadow semi-transparent
                g2d.setColor(new Color(
                    color.getRed(),
                    color.getGreen(),
                    color.getBlue(),
                    (int)(255 * (1 - progress) * 0.2)
                ));
                
                // Offset each shadow layer based on angle
                AffineTransform shadowTransform = new AffineTransform(transform);
                shadowTransform.translate(i * 2 * Math.cos(angle), i * 2 * Math.sin(angle));
                g2d.setFont(baseFont.deriveFont(shadowTransform));
                g2d.drawString(text, 0, 0);
                
            }
            
            // Draw main text with animated gradient
            GradientPaint gradient = new GradientPaint(
                x, y - metrics.getHeight(),
                getGradientColor(time * 0.1f),
                x + textWidth, y,
                getGradientColor(time * 0.1f + 0.5f)
            );
            
           g2d.setFont(scaledFont);
           g2d.setPaint(gradient);
           g2d.drawString(text, 0, 0);
        
            // Add shine effect (diagonal highlight across the text)
            g2d.setClip(new TextLayout(text, scaledFont, g2d.getFontRenderContext()).getOutline(null));
            g2d.setPaint(new GradientPaint(
                x, y - metrics.getHeight() * 2,
                new Color(255, 255, 255, 50),  // Semi-transparent white
                x, y,
                new Color(255, 255, 255, 0)    // Fully transparent
            ));
            g2d.fillRect(x, y - metrics.getHeight() * 2,
                        textWidth, metrics.getHeight() * 3);
            g2d.setClip(null);
        
    }
    
    
     /**
     * Calculates a color from the gradient based on position
     * 
     * @param position A float value (will be wrapped to 0.0-1.0)
     * @return Interpolated color from the gradient
     */
      private Color getGradientColor(float position) {
          
            // Ensure position is between 0.0 and 1.0
           position = position % 1.0f;
           if (position < 0) position += 1.0f;
           
           // Find the two colors to interpolate between
            float scaled = position * (gradientColors.length - 1);
            int index = (int) scaled;
            float fraction = scaled - index;
            
            Color c1 = gradientColors[index];
            Color c2 = gradientColors[(index + 1) % gradientColors.length];
            
            // Interpolate between the two colors
            return new Color(
                lerp(c1.getRed(), c2.getRed(), fraction) / 255f,
                lerp(c1.getGreen(), c2.getGreen(), fraction) / 255f,
                lerp(c1.getBlue(), c2.getBlue(), fraction) / 255f
            );
            
          
      }
    
    
    
    
     /**
     * Linear interpolation function
     * 
     * @param start Starting value
     * @param end Ending value
     * @param fraction How far between start and end (0.0-1.0)
     * @return Interpolated value
     */
     private int lerp(int start, int end, float fraction) {
        return (int) (start + (end - start) * fraction);
    }
    
}

  

The Final Result:


Java Text Animation 1

Java Text Animation 2

Java Text Animation 3





Python Tkinter Data Table Pagination

How to Create a Paginated Data Table in Python Tkinter

How to Create a Paginated Data Table in Python Tkinter




In this Python Tutorial we will see How to Create a Table in Python Tkinter with advanced pagination, navigation controls, and professional styling.


What We're Building ?

We're creating a sophisticated data table with:

- Dynamic pagination with customizable page sizes (5, 10, 15, 20 rows).
- Smart navigation controls with first/last/previous/next buttons.
- Page number buttons with intelligent ellipsis handling.
- Jump-to-page functionality with input validation.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter (GUI).
- VS Editor.






Project Source Code:




import tkinter as tk
from tkinter import ttk
import random
from typing import List, Tuple
import math

class PaginatedTable(tk.Tk):

def __init__(self):

super().__init__()

# Define color scheme for the application
self.primary_color = "#4F46e5"
self.hover_color = "#c7d2fe"
self.bg_color = "#f9fafb"
self.text_color = "#111827"

# Initialize pagination-related variables
# Start with first page
self.current_page = 1
# Number of rows to show per page
self.records_per_page = 5
# List to store all table data
self.all_data: List[Tuple] = []

self.setup_window()
self.create_styles()
self.initialize_components()
self.load_simple_data()
self.update_table()
self.center_window()


def setup_window(self):
self.title("Paginated Table")
self.geometry("900x620")
self.configure(bg=self.bg_color)
def center_window(self):
# Update window's actual dimensions
self.update_idletasks()
# Get window dimensions
width = self.winfo_width()
height = self.winfo_height()
# Calculate position to center window
x = (self.winfo_screenwidth() // 2) - (width // 2)
y = ((self.winfo_screenheight()-20) // 2) - (height // 2)
print(self.winfo_screenheight())
print(height)
# Set window position
self.geometry(f'{width}x{height}+{x}+{y}')
def initialize_components(self):
# Create main container frame
self.main_frame = tk.Frame(self, bg=self.bg_color, padx=20, pady=20)
self.main_frame.pack(fill=tk.BOTH, expand=True)

# Create white container for table
self.table_container = tk.Frame(self.main_frame, bg="white",
bd=1, relief="solid")
self.table_container.pack(fill=tk.BOTH, expand=True)

# Define table columns
columns = ("ID", "Name", "Email", "Status")

# Create table widget
self.table = ttk.Treeview(self.table_container, columns = columns,
show="headings", style="Modern.Treeview", selectmode="browse")

# Configure each column in table
for col in columns:
self.table.heading(col, text = col, anchor = "w")
self.table.column(col, anchor="w", width=100)
# Add vertical scrollbar
scrollbar = ttk.Scrollbar(self.table_container, orien="vertical",
command=self.table.yview)
self.table.configure(yscrollcommand=scrollbar.set)

# Arrange table and scrollbar
self.table.pack(side="left", fill="both", expand="True")
scrollbar.pack(side="right", fill="y")

# Create frame for pagination controls
self.pagination_frame = tk.Frame(self.main_frame, bg="white", height=60)
self.pagination_frame.pack(fill="x", pady=(20, 0))

# Create left section with page size selector
left_frame = tk.Frame(self.pagination_frame, bg="white")
left_frame.pack(side="left", padx=10)

# Create dropdown for selecting number of rows per page
self.page_size_var = tk.StringVar(value = "5 rows")
page_sizes = ["5 rows", "10 rows", "15 rows", "20 rows"]
self.page_size_combo = ttk.Combobox(left_frame, values = page_sizes,
textvariable = self.page_size_var,
style="Modern.TCombobox", width=10)
self.page_size_combo.pack(side="left", padx=5)
self.page_size_combo.bind('<<ComboboxSelected>>', self.on_page_size_change)

# Create label showing total records
self.total_records_label = tk.Label(left_frame, text="Total: 0 records",
bg="white", fg=self.text_color, font=("Arial", 11))
self.total_records_label.pack(side="left", padx=10)

# Create center frame for page navigation
self.center_frame = tk.Frame(self.pagination_frame, bg="white")
self.center_frame.pack(side="left", expand="True")

# Create right section for page jump
right_frame = tk.Frame(self.pagination_frame, bg = "white")
right_frame.pack(side="right", padx=10)

# Add "Go to page" label
tk.Label(right_frame, text="Go to page: ", bg="white", fg=self.text_color,
font=("Arial", 11)).pack(side="left")
# Create entry field for jumping to specific page
self.page_jump = tk.Entry(right_frame, width=5, font=("Arial", 11))
self.page_jump.pack(side="left", padx=5)
self.page_jump.bind("<Return>", self.on_page_jump)




def create_styles(self):
# Create style object for themed widgets
style = ttk.Style()
style.theme_use("clam")

# Configure style for table (Treeview)
style.configure("Modern.Treeview", background="white",
foreground=self.text_color, rowheight=50, fieldbackground = "white",
borderwidth = 0, font = ("Arial", 11))


# Configure style for table header (Treeview)
style.configure("Modern.Treeview.Heading", background="black",
foreground="white", borderwidth = 0, font = ("Inter", 11, 'bold'))

# Configure table selection colors
style.map("Modern.Treeview", background = [('selected', self.hover_color)],
foreground = [('selected', "red")])

# Configure style for dropdown (Combobox)
style.configure("Modern.TCombobox", background="white",
foreground=self.text_color, arrowcolor = "red")




def load_simple_data(self):
# Define possible status values
statuses = ["Active", "Pending", "Completed", "Inactive"]
self.all_data = []

# Generate 1000 sample records
for i in range(1, 1000):
self.all_data.append(
(f"#{i:03d}",
f"User{i}",
f"user{i}@example.com",
random.choice(statuses))
)
# Calculate total pages needed
self.total_pages = math.ceil(len(self.all_data) / self.records_per_page)



def create_pagination_button(self, parent, text, command, is_active = False):
# Create a button for pagination navigation
btn = tk.Button(parent, text = text, font=("Arial", 11),
bg = self.primary_color if is_active else "white",
fg = "white" if is_active else self.text_color,
bd = 1 if not is_active else 0,
relief = "solid" if not is_active else "flat",
width=3, height = 1, command=command)
btn.pack(side="left", padx = 2)
return btn


def update_table(self):
# Remove all existing rows
for item in self.table.get_children():
self.table.delete(item)
# Calculate which records to show
start = (self.current_page - 1) * self.records_per_page
end = start + self.records_per_page

# Add records for current page
for row in self.all_data[start: end]:
self.table.insert("", "end", values = row)

# Update pagination buttons
self.update_pagination()


def go_to_page(self, page):
# Change page if requested page is valid
if 1 <= page <= self.total_pages:
self.current_page = page
self.update_table()

def on_page_size_change(self, event):
# Get selected number of rows per page
size = int(self.page_size_var.get().split()[0])
# Update pagination settings
self.records_per_page = size
self.total_pages = math.ceil(len(self.all_data) / self.records_per_page)
self.current_page = 1
# Refresh table display
self.update_table()

def on_page_jump(self, event):
try:
# Try to convert entered page number to integer
page = int(self.page_jump.get())

# Go to page if number is valid
if 1 <= page <= self.total_pages:
self.go_to_page(page)

# Clear the entry field
self.page_jump.delete(0, tk.END)
except ValueError:
pass

def update_pagination(self):
# Clear existing pagination buttons
for widget in self.center_frame.winfo_children():
widget.destroy()

# Add first page button
self.create_pagination_button(self.center_frame, "⟪",
lambda: self.go_to_page(1), False)
# Add previous page button
self.create_pagination_button(self.center_frame, "←",
lambda: self.go_to_page(self.current_page - 1), False)

# Calculate which page numbers to show
start = max(1, self.current_page - 2)
end = min(self.total_pages, start + 4)

# Add ellipsis if needed at start
if start > 1:
tk.Label(self.center_frame, text = "...", bg="white").pack(side="left",
padx = 5)

# Add page number buttons
for i in range(start, end + 1):
self.create_pagination_button(self.center_frame, str(i),
lambda x = i: self.go_to_page(x),
i == self.current_page)

# Add ellipsis if needed at end
if end < self.total_pages:
tk.Label(self.center_frame, text = "...", bg="white").pack(side="left",
padx = 5)

# Add next page button
self.create_pagination_button(self.center_frame, "→",
lambda: self.go_to_page(self.current_page + 1), False)

# Add last page button
self.create_pagination_button(self.center_frame, "⟫",
lambda: self.go_to_page(self.total_pages), False)

# Update total records counter
self.total_records_label.config(text = f"Total: {len(self.all_data)} records")


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



The Final Result:

Python Tkinter Data Table Pagination