How to draw a wave form pattern in java swing

In this program, we will learn how to draw waveform pattern in Java. Here, we use the AWT and swing package. We use many classes and methods of AWT and Swing packages. Now we see & understand the java program.

Java program to create wave form pattern

Here is the Java code to create wave form pattern using AWT and Swing package.

import java.awt.*;
import javax.swing.*;

public class WavePrint extends JPanel 
  int SCALEFACTOR = 200;
  int cycles;
  int points;
  double[] sines;
  int[] pts;

  public  void setCycles(int cycles) 
    this.cycles = cycles;
    this.points = SCALEFACTOR * cycles * 2;
    this.sines = new double[points];
    for (int i = 0; i < points; i++) 
      double radians = (Math.PI / SCALEFACTOR) * i;
      this.sines[i] = Math.sin(radians);

  public void paintComponent(Graphics g) 
    int maxWidth = getWidth();
    double hstep = (double) maxWidth / (double) points;
    int maxHeight = getHeight();
    pts = new int[points];
    for (int i = 0; i < points; i++)
      pts[i] = (int) (sines[i] * maxHeight / 2 * .95 + maxHeight / 2);
    for (int i = 1; i < points; i++) 
      int x1 = (int) ((i - 1) * hstep);
      int x2 = (int) (i * hstep);
      int y1 = pts[i - 1];
      int y2 = pts[i];
      g.drawLine(x1, y1, x2, y2);

  public static void main(String[] args) 
    JFrame frame = new JFrame("Print the wave pattern");
    frame.setSize(500, 200);

    WavePrint sw = new WavePrint();

In this program, we import the Swing & AWT package. We use frame and get Width and get Height methods. get Width method return the width of an applet & get Height method return the value of a height of an applet. we use graphics also in this program for the display the pattern and we use many methods of a graphics package. We also, use setColor for the colors. Please read the code carefully and try to understand. Although it is an easy for beginners

Output of the program

wave from pattern in java swing

output: Wave form pattern in Java

You may also read,

Leave a Reply

Your email address will not be published. Required fields are marked *