Java Animated Sonic Waves Source Code

How to Create a Sonic Waves animation In Java Netbeans

How to Create a Sonic Waves animation In Java Netbeans


In this Java Tutorial we will see How To Create a Sonic Waves animation that display 7 vertical bars that pulse up and down in a wave pattern with Realistic reflections below the baseline and a  Smooth sine wave animation patterns In Java Swing Using Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:




/**
 *
 * @author 1BestCsharp
 */
public class SonicWaves extends JPanel{

    // Constants that control the appearance of the bars
    private static final int BAR_COUNT = 7;         // Total number of bars to display
    private static final int BAR_WIDTH = 6*2;         // Width of each bar in pixels
    private static final int BAR_GAP = 6*2;           // Space between bars in pixels
    private static final int BAR_HEIGHT = 70*2;       // Maximum height of bars in pixels
    private static final int ANIMATION_DELAY = 1500; // Time in milliseconds for a complete animation cycle
    
    // Array of neon colors used for the bars
    private final Color[] colors = {
            new Color(0, 238, 255),   // neon blue
            new Color(179, 0, 255),   // neon purple
            new Color(255, 0, 255),   // neon pink
            new Color(10, 255, 170)   // neon teal
    };
    
    private final float[] barHeights;  // Stores the current height of each bar (as a fraction from 0.0 to 1.0)
    private final Timer timer;         // Timer that controls the animation
    private int colorIndex = 0;        // Index of the current color in the colors array
    
    public SonicWaves(){
        
        // Set the preferred size for this panel
        setPreferredSize(new Dimension(BAR_COUNT * (BAR_WIDTH + BAR_GAP), BAR_HEIGHT * 2 + 60));
        // Set dark background color
        setBackground(new Color(15, 15, 26));
        
        // Initialize all bars with a small height (0.2 = 20% of maximum height)
        barHeights = new float[BAR_COUNT];
        for (int i = 0; i < BAR_COUNT; i++) {
            barHeights[i] = 0.2f; 
        }
        
        // Create a timer that will update the animation every 40 milliseconds
        timer = new Timer(40, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
                updateBarHeights();  // Calculate new heights for the bars
                repaint();           // Redraw the panel with the new heights
                
            }
        });
        
        // Start the animation timer
        timer.start();
        
    }
    
    
     /**
     * Updates the height of each bar based on a sine wave pattern
     */
    private void updateBarHeights() {
        
        // Get the current system time in milliseconds
        long currentTime = System.currentTimeMillis();
        
        // Calculate new height for each bar
        for(int i = 0; i < BAR_COUNT; i++){
            
            // Calculate a phase offset for each bar to create a wave effect
            double phaseOffset = i * (Math.PI / 8);
            
            // Calculate the current progress through the animation cycle (0.0 to 1.0)
            double progress = (currentTime % ANIMATION_DELAY) / (double) ANIMATION_DELAY;
            
            // Calculate angle for sine wave
            double angle = 2 * Math.PI * progress + phaseOffset;
            
            // Calculate new bar height using sine wave (range from 0.2 to 1.0)
            barHeights[i] = (float) (0.2f + 0.8f * Math.abs(Math.sin(angle)));
            
            // Change colors at the beginning of each animation cycle
            if (currentTime % ANIMATION_DELAY < 50) {
                colorIndex = (colorIndex + 1) % colors.length;
            }
            
        }
        
    }
    
    
    
    
    
     /**
     * This method is called automatically whenever the panel needs to be redrawn
     */
    @Override
    protected void paintComponent(Graphics g){
        
        // Call the parent class's paintComponent method first
        super.paintComponent(g);
        // Create a Graphics2D object for more advanced drawing
        Graphics2D g2d = (Graphics2D) g.create();
        // Enable anti-aliasing for smoother lines and shapes
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        
        // Calculate the total width needed for all bars
        int totalWidth = BAR_COUNT * (BAR_WIDTH + BAR_GAP) - BAR_GAP;
        
        // Calculate starting X position to center the bars
        int startX = (getWidth() - totalWidth) / 2;
        // Calculate Y position for the base of the bars
        int baseY = getHeight() / 2 - 20;
        
        // Draw the glowing background
        drawBackgroundGlow(g2d);
        
        // Draw each bar and its reflection
        for(int i = 0; i < BAR_COUNT; i++){
            
            // Calculate the X position for this bar
            int x = startX + i * (BAR_WIDTH + BAR_GAP);
            // Calculate the height for this bar in pixels
            int height = (int) (barHeights[i] * BAR_HEIGHT);
            // Calculate the Y position for the top of the bar
            int y = baseY - height;
            
            // Get a color for this bar (shifts colors between bars)
            Color barColor = colors[(colorIndex + i) % colors.length];
            
            // Draw the main bar
            drawBar(g2d, x, y, height, barColor);
            
             // Draw the reflection of the bar below the baseline
            drawReflection(g2d, x, baseY, height, barColor);
            
        }
        
         // Draw the "Sonic Wave" text label
        drawLabel(g2d, baseY + BAR_HEIGHT + 30);
        
        
        // Clean up the Graphics2D object
        g2d.dispose();
        
    }
    
    
    
     /**
     * Draws a glowing background effect
     */
    private void drawBackgroundGlow(Graphics2D g2d){
        
        // Calculate center of the panel
        int centerX = getWidth() / 2;
        int centerY = getHeight() / 2;
        
        // Calculate radius for the gradient
        int radius = Math.max(getWidth(), getHeight()) / 2;
        
        // Create a radial gradient paint (a gradient that radiates from the center)
        RadialGradientPaint glow = new RadialGradientPaint(
                centerX, centerY, radius,  // Center and radius
                new float[] {0.0f, 0.7f, 1.0f},  // Positions for color stops (0=center, 1=edge)
                new Color[] {  // Colors at each position
                    new Color(30, 30, 50),    // Slightly lighter color at center
                    new Color(20, 20, 35),    // Middle color
                    new Color(15, 15, 26)     // Darker color at edge
                }
        );
        
        // Set the gradient as the current paint
        g2d.setPaint(glow);
        // Fill the entire panel with the gradient
        g2d.fillRect(0, 0, getWidth(), getHeight());
        
    }
    
    
     /**
     * Draws a single bar with glowing effect
     */
    private void drawBar(Graphics2D g2d, int x, int y, int height, Color barColor) {
        
         // Create a gradient for the bar that transitions from white to the bar color
        GradientPaint gradient = new GradientPaint(
                x, y, new Color(255, 255, 255, 220),  // Start with semi-transparent white at top
                x, y + height, barColor);             // End with the bar color at bottom
        
        // Set the gradient as the current paint
        g2d.setPaint(gradient);
        
        // Create a rounded rectangle shape for the bar
        RoundRectangle2D bar = new RoundRectangle2D.Float(x, y, BAR_WIDTH, height, 4, 4);
        // Fill the shape with the gradient
        g2d.fill(bar);
        
        // Save the original composite (transparency) setting
        Composite originalComposite = g2d.getComposite();
        
        // Draw several layers of outlines to create a glow effect
        for(int j = 1; j <= 5; j++){
            
            // Calculate decreasing alpha (transparency) for each outer layer
            float alpha = 0.5f - (j * 0.08f);
            
            // Set the transparency level
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
            
            // Set the color for the glow
            g2d.setColor(barColor);
            
            // Draw a slightly larger outline around the bar
            g2d.draw(new RoundRectangle2D.Float(x - j, y - j, BAR_WIDTH + 2*j, height + 2*j, 4, 4));
            
        }
        
        // Restore the original composite setting
        g2d.setComposite(originalComposite);
        
    }
    
    
    
     /**
     * Draws the reflection of a bar below the baseline
     */
    private void drawReflection(Graphics2D g2d, int x, int baseY, int height, Color barColor) {
        
        // Save the original composite (transparency) setting
        Composite originalComposite = g2d.getComposite();
        
        // Draw the reflection one line at a time with decreasing opacity
        for(int i = 0; i < height; i++){
            
            // Calculate decreasing opacity as we move down the reflection
            float alphaFactor = 0.4f * (1.0f - ((float)i / height));
            
            // Set the transparency level
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alphaFactor));
            
            // Create a slightly darker color for the reflection
            Color reflectionColor = new Color(
                Math.max(barColor.getRed() - 20, 0),     // Reduce red component (minimum 0)
                Math.max(barColor.getGreen() - 20, 0),   // Reduce green component
                Math.max(barColor.getBlue() - 20, 0)     // Reduce blue component
            );
            
            // Calculate the Y position for this line of the reflection
            int reflectionY = baseY + i;
            // Set the color for this line
            g2d.setColor(reflectionColor);
            // Draw a single line of the reflection
            g2d.fillRoundRect(x, reflectionY, BAR_WIDTH, 1, 2, 2);          
            
        }
        
        // Add a subtle shimmering effect that changes over time
        // Calculate sine wave based on current time for shimmering effect
        float rippleEffect = (float)(Math.sin(System.currentTimeMillis() / 200.0) * 0.1 + 0.2);
        // Set transparency for the shimmer
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, rippleEffect));
        // Set a very light color for the shimmer
        g2d.setColor(new Color(255, 255, 255, 40));
        // Draw a semi-transparent overlay on top of the reflection
        g2d.fillRoundRect(x, baseY, BAR_WIDTH, height / 2, 2, 2);
        
        // Restore the original composite setting
        g2d.setComposite(originalComposite);
        
    }
    
    
     /**
     * Draws the "SONIC WAVE" text label
     */
    private void drawLabel(Graphics2D g2d, int y) {
        
        // Text to display
        String label = "SONIC WAVE";
        
        // Set font for the text
        g2d.setFont(new Font("Verdana", Font.BOLD, 24));
        
        // Get font metrics to measure text width
        FontMetrics fm = g2d.getFontMetrics();
        int textWidth = fm.stringWidth(label);
        
        // Calculate X position to center text
        int textX = (getWidth() - textWidth) / 2;
        
        // Draw glowing effect behind text using current color theme
        g2d.setColor(new Color(colors[colorIndex].getRed(), 
                              colors[colorIndex].getGreen(), 
                              colors[colorIndex].getBlue(), 40));  // Semi-transparent
        
        // Draw multiple offset copies of the text to create a glow
        for (int i = 1; i <= 5; i++) {
            g2d.drawString(label, textX - i/2, y + i/2);  // Offset one direction
            g2d.drawString(label, textX + i/2, y - i/2);  // Offset other direction
        }
        
        // Draw the main text in white
        g2d.setColor(new Color(255, 255, 255, 220));
        g2d.drawString(label, textX, y);
        
        // Set up parameters for decorative lines
        int lineLength = 40;  // Length of each line
        int lineY = y + 8;    // Y position (slightly below text)
        int gap = 10;         // Gap between text and lines
        
        // Set color and line thickness for the decorative lines
        g2d.setColor(colors[colorIndex]);
        g2d.setStroke(new BasicStroke(1.5f));
        
        // Draw line to the left of the text
        g2d.drawLine(textX - gap - lineLength, lineY, textX - gap, lineY);
        
        // Draw line to the right of the text
        g2d.drawLine(textX + textWidth + gap, lineY, textX + textWidth + gap + lineLength, lineY);
        
    }
    
    
    
     /**
     * Stops the animation timer when the component is no longer needed
     */
    public void stopAnimation() {
        if (timer.isRunning()) {
            timer.stop();
        }
    }
    
    
    
    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(() -> {
        
             // Create a frame window
            JFrame frame = new JFrame("Sonic Wave Spinner");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
             // Create a dark panel to hold the spinner
            JPanel darkPanel = new JPanel(new BorderLayout());
            darkPanel.setBackground(new Color(15, 15, 26));
            darkPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
            
            // Create and add the waves component
            SonicWaves waves = new SonicWaves();
            darkPanel.add(waves, BorderLayout.CENTER);
            
            // Add the panel to the frame and display it
            frame.getContentPane().add(darkPanel);
            frame.pack();
            frame.setSize(600, 500);
            frame.setLocationRelativeTo(null);  // Center on screen
            frame.setVisible(true);
            
        });
        
    }
    
}
  


The Final Result:

Java Animated Sonic Waves Source Code

Java Animated Sonic Waves

Java Sonic Waves Animation Source Code







Banking Application Using HTML, CSS And Javascript

How To Create a Banking Application in JavaScript, HTML and CSS

How To Create a Banking Application in JavaScript, HTML and CSS


In this JavaScript Tutorial, we will see how to create a simple banking application using  JavaScript, HTML5, CSS3 and Chart.js .
We'll build a financial dashboard that includes real-time balance tracking, interactive transaction management, dynamic chart visualization, and a responsive user interface.
This banking project demonstrates essential web development concepts including DOM manipulation, event handling, data visualization with Chart.js, CSS Grid and Flexbox layouts.

What We Are Gonna Use In This Project:

- JavaScript Programming Language.
- HTML and CSS.
Chart.js .
- Visual Studio Editor.





Project Source Code:



     - Chart Initialization

Creates and configures the interactive balance chart using Chart.js.


// Create the chart for balance history
function initChart() {

const ctx = document.getElementById('balance-chart').getContext('2d');

chart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Balance',
data: [],
borderColor: '#FF7600',
backgroundColor: 'rgba(255, 118, 0, 0.1)',
tension: 0.4,
fill: true
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
grid: {
color: 'rgba(255, 255, 255, 0.05)'
},
ticks: {
color: '#B0B0B0'
}
},
x: {
grid: {
display: false
},
ticks: {
color: '#B0B0B0',
maxRotation: 0,
maxTicksLimit: 5
}
}
},
plugins: {
legend: {
display: false
},
tooltip: {
mode: 'index',
intersect: false,
backgroundColor: 'rgba(30, 30, 30, 0.9)',
titleColor: '#FFFFFF',
bodyColor: '#FFFFFF',
borderColor: '#FF7600',
borderWidth: 1
}
}
}
});

}



     - Balance Display Updates.
    
A simple function that updates the balance display on the screen.


// Update the balance display
function updateBalance() {
// Show balance with 2 decimal places
balanceElement.textContent = `$${balance.toFixed(2)}`;
}



     - Transaction Recording.

This function handles the creation of new transactions.
 

// Add a new transaction to history
function addTransaction(type, amount) {
// Create a transaction object with type, amount and date
const transaction = {
type, // 'deposit' or 'withdraw'
amount,
date: new Date() // Current date and time
};

// Add to transactions list
transactions.push(transaction);

// Update the display
updateTransactionHistory();
updateChart();

// Reset scroll to top to show newest transactions
transactionHistory.scrollTop = 0;

}



     - Transaction History.

Display all the transactions (↑ for deposits, ↓ for withdrawals).


// Update the transaction history display
function updateTransactionHistory() {
// Clear the current list
transactionHistory.innerHTML = '';

// Loop through transactions in reverse order (newest first)
transactions.slice().reverse().forEach((transaction, index) => {
// Create a new transaction element
const transactionElement = document.createElement('div');
transactionElement.classList.add('transaction', transaction.type);

// Set icon based on transaction type
const iconContent = transaction.type === 'deposit' ? '↑' : '↓';

// Fill in the transaction details
transactionElement.innerHTML = `
<div class="transaction-icon">${iconContent}</div>
<div class="transaction-info">
<span class="transaction-type">${transaction.type}</span>
<span class="transaction-date">
                                        ${transaction.date.toLocaleString()}</span>
</div>
<span class="transaction-amount">
                                            $${transaction.amount.toFixed(2)}</span>
`;

// Add animation to make it fade in
transactionElement.style.animation =
                                        `fadeIn 0.3s ease-out ${index * 0.05}s both`;
transactionHistory.appendChild(transactionElement);

});
}



     - Chart Data Updates.

Keeps the balance chart synchronized with transaction data.


// Update the chart with new data
function updateChart() {
// Create labels (T1, T2, etc.) for each transaction
chart.data.labels = transactions.map((_, index) => `T${index + 1}`);

// Calculate running balance for each point
let runningBalance = 0;
chart.data.datasets[0].data = transactions.map(transaction => {
// Add amount for deposits, subtract for withdrawals
runningBalance += transaction.type === 'deposit' ?
                                            transaction.amount : -transaction.amount;
return runningBalance;
});

// Update the chart
chart.update();
}



     - Display error message.


// Show error popup
function showError(message) {
// Set the error message
errorMessage.textContent = message;
// Show the modal
errorModal.style.display = 'block';
errorModal.classList.add('show');
}



     - Dismiss The Error Message.


// Hide error popup
function hideError() {
// Start the hiding animation
errorModal.classList.remove('show');
// After animation finishes, hide the modal
setTimeout(() => {
errorModal.style.display = 'none';
}, 300);
}



     - Transaction Processing.


// Handle deposit or withdraw
function handleTransaction(type) {
// Get amount from input and convert to number
const amount = parseFloat(amountInput.value);

// Check if amount is valid
if (isNaN(amount) || amount <= 0) {
showError('Please enter a valid positive number');
return;
}

// Check if there's enough money for withdrawal
if (type === 'withdraw' && amount > balance) {
showError('Insufficient funds');
return;
}

// Update balance
balance += type === 'deposit' ? amount : -amount;

// Add to transaction history
addTransaction(type, amount);

// Update balance display
updateBalance();

// Clear input field
amountInput.value = '';
}



     - Button Click Handlers.


// Button click events
depositBtn.addEventListener('click', () => handleTransaction('deposit'));
withdrawBtn.addEventListener('click', () => handleTransaction('withdraw'));



     - Date Display.


// Show today's date in the header
currentDateElement.textContent = new Date().toLocaleDateString('en-US', {
year: 'numeric', month: 'long', day: 'numeric'
});