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.*;
public class SinusoidApp
{
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(300, 200));
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 = (int) Math.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