|
An exception occurred - please try again.
This code sample shows how to draw a sine curve. It is based on code "posted here"http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=33&t=023282 by Adrian Sosialuk and Jesper Young. Optionally, a line connecting the data points can be shown.
J[
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(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; i0)
{
g.drawLine(i-1, previousY, i, y);
} else {
g.drawLine(i, y, i, y);
}
previousY = y;
}
}
}
}
]
----
CategoryCodeSamples CodeBarn
|