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:
More Java Projects:
Download Projects Source Code



