Draw Sine Graph with Java Code

by Azeem Tariq

Posted 1 year ago

Last Updated 9 months ago

2205 views

Draw Sine Graph with Java Code

Maths and computer science is fun :) . In this post we will draw Graph of Sine with java code. Here is the graph of Sine with respect to angle.  

sine-graph with java

lets plot this graph with java code ,

Java Code To Draw Graph of Sine

Main.java Class

import javax.swing.JFrame;

public class Main {
    
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setSize(900, 700);
        frame.setTitle("Sin(x) Graph ~ RadixCode.com");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.getContentPane().add(new SinX());
        frame.setVisible(true);
    }
}

and here is SinX.java class that i use in previous Main.java class

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import static java.lang.Math.*;

public class SinX extends Component {
    
    public void paint(Graphics g)
    {
        g.drawLine(0,350,900,350); // x-axis
        g.drawLine(450,0,450,900); // y-axis
        
        g.setColor(Color.red);
        
        for(double x=-450;x<=450;x=x+0.5)
        {
            double y = 50 * sin(x*(3.1415926/180));
            int Y = (int)y;
            int X = (int)x;
            g.drawLine(450+X,350-Y,450+X,350-Y);
        }
    }
}

 Example output

grpah of sine with java code

Download this Complete Java Project from here