JavaRanch Home    
 
This page:         last edited 30 May 2010         What's Changed?         Edit

Plot Sine Curve   

This code sample shows how to draw a sine curve. It is based on code posted here by Adrian Sosialuk and Jesper Young. Optionally, a line connecting the data points can be shown.


import java.awt.*;
import javax.swing.*;
 
/**
 * This class plots a sine curve between -2*PI and 2*PI.
 */
 
public class SinusoidApp
{

    // whether or not to draw a connecting line between the dots
    static boolean drawConnectingLine = true;

    public static void main (String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
                Sinusoid s = new Sinusoid();
                s.setPreferredSize(new Dimension(300200));
                frame.getContentPane().add(s);
 
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    static class Sinusoid extends JPanel
    {
        int previousY = 0;

        double degToRad (int deg)
        {
            return ((2*Math.PI)/360.0) * deg;
        }

        int scale (int i, int width)
        {
            return (int) ((i/(double)width)*720.0);
        }

        public void paintComponent (Graphics g)
        {
            super.paintComponent(g);
            int width = getWidth();
            int height = getHeight();
            for (int i=0; i<width; i++)
            {
                int y = (intMath.round((-Math.sin(degToRad(scale(i,width)))+1)*height/2.0);
                if (drawConnectingLine && i>0)
                {
                    g.drawLine(i-1, previousY, i, y);
                } else {
                    g.drawLine(i, y, i, y);
                }
                previousY = y;
            }
        }
    }
}


CategoryCodeSamples CodeBarn

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton