Draw Cosine Graph with Java Code

Posted 2 years ago

Last Updated 1 year ago

856 views Draw Cosine Graph with Java Code

Hi welcome back , in this post i  am sharing java code to draw Cosine graph , lets first have a look at Cosine Graph its really simple to draw this graph with java. here is the java code

Java Code To Draw Cosine Graph

Main.java class with main method

import javax.swing.JFrame;

public class Main {

public static void main(String[] args) {

JFrame frame = new JFrame();
frame.setSize(900, 700);
frame.setTitle("Cos(x) Graph ~ RadixCode.com");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
}

}

and here is the CosX.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.cos;

public class CosX 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 * cos(x*(3.1415926/180));
int Y = (int)y;
int X = (int)x;
g.drawLine(450+X,350-Y,450+X,350-Y);
}
}
}

Output 