Create Sine Wave

Here you will learn how to create Sine Wave.

Ads

Tutorials   
Ads

Create Sine Wave

     

In this section, you will learn how to create a Sine Wave using Java Swing. We have used Graphics class to draw the Sine Wave. To set the number of cycles, we have created the following method:

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

Here is the code of SineWave.java:

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

class Diagram extends JPanel {
 static final int SCALEFACTOR = 200;
 int cycles;
 int points;
 double[] sines;
 int[] pts;
 Diagram() {
 
  }
  public  void setCycles(int newCycles) {
  cycles = newCycles;
  points = SCALEFACTOR * cycles * 2;
  sines = new double[points];
  for (int i = 0; i < points; i++) {
  double radians = (Math.PI / SCALEFACTOR* i;
  sines[i= Math.sin(radians);
  }
  repaint();
  }
  public void paintComponent(Graphics g) {
  super.paintComponent(g);
  int maxWidth = getWidth();
  double hstep = (doublemaxWidth / (doublepoints;
  int maxHeight = getHeight();
  pts = new int[points];
  for (int i = 0; i < points; i++)
  pts[i(int) (sines[i* maxHeight / .95 + maxHeight / 2);
  g.setColor(Color.BLUE);
  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 class SineWave {
 public static void main(String[] args) {
 JFrame frame = new JFrame();
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setSize(500200);
  Diagram sines = new Diagram();
  sines.setCycles(5);
  frame.getContentPane().add(sines);
  frame.setVisible(true);
  }

Output will be displayed as:

Download Source Code:

 

Advertisements

Share on Google+Share on Google+

Create Sine Wave

Posted on: October 15, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Create Sine Wave  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads