I am a beginner in Java Swing . I was trying to draw the graph of sin(x) in applet . I am surprised why applet always draws my axis only not my graph? here is my code :
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class NewApplet extends Applet
{
public void init()
{
// TODO start asynchronous download of heavy resources
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
//get dimension
Dimension appletSize = this.getSize();
// make the applet empty at start
g2.setBackground(Color.white);
g2.setColor(Color.white);
g2.fillRect(0, 0, appletSize.width, appletSize.height);
//now draw all you need
g2.setColor(Color.red);
//x axis
g2.drawLine(0, appletSize.height/2, appletSize.width, appletSize.height/2);
//y axis
g2.drawLine(appletSize.width/2, 0, appletSize.width/2, appletSize.height);
//function
g2.setColor(Color.black);
for(int k=0; k<=180; k++)
{
g2.drawString(".", (float) Math.toRadians(k), (float) Math.sin(Math.toRadians(k)));
}
}
}
I am plotting 180 points of sin(x) with String
"." , but My applet didn't show a single plot.Why?
[ Mention if there any good practice I should follow or suggest me any good library (JAR) for drawing graphs ]
It actually draws a graph.
Since values sine are between -1 and +1, and the radian values are between0 +π and -π, so the graph is drawn at those coordinates.
If you change this line:
g2.drawString(".", (float) Math.toRadians(k), (float) Math.sin(Math.toRadians(k)));
to this line:
g2.drawString(".", (appletSize.height/2)+(float) Math.toRadians(k)*50, (appletSize.width/2)+(float) Math.sin(Math.toRadians(k))*50);
You will see half the graph (since you have written the code for half the graph.)
Here:
(appletSize.height/2)
and (appletSize.width/2)
to the values, to bring them to the center of the screen (on the graph)