Affichage des articles dont le libellé est Java Swing Text Animation. Afficher tous les articles
Affichage des articles dont le libellé est Java Swing Text Animation. Afficher tous les articles

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