在java中绘制sin(x)的图形

我目前正在尝试在java中绘制sin(x)的图形。 我的指令要求我只使用drawLine()作为绘制图形的方法。 我似乎无法弄清楚如何正确设置我的y值。 现在我所拥有的是一个while循环,用于逐个像素地绘制线条,但无法设法让y值正确。 这是我到目前为止所拥有的。

public class GraphJComponent extends JComponent { public void paintComponent (Graphics g){ Color axis = new Color(128, 128, 128); g.setColor(axis); int xShift = getWidth() / 50; int xShift2 = getWidth() / 100; int yShift = getHeight() / 10; int yShift2 = getHeight() / 17; g.drawLine(xShift,yShift,xShift,getHeight() - yShift); g.drawLine(xShift, getHeight() / 2, getWidth() - xShift, getHeight() / 2); g.drawString("0", xShift + xShift2, getHeight() / 2 + yShift2); g.drawString("1", xShift + xShift2, yShift - (yShift2 / 4)); g.drawString("-1", xShift + xShift2, getHeight() - yShift + yShift2); g.drawString("\u03c0", getWidth() / 2, getHeight() / 2 + yShift2); g.drawString("2" + "\u03c0", getWidth() - (2 * xShift), getHeight() / 2 + yShift2); Color line = new Color (255, 0, 0); g.setColor(line); int x = xShift; int y = getHeight() / 2; while (x < getWidth() - xShift){ x += 1; y = ??; g.drawLine(x, y, x, y); } } 

}

是的我知道有很多东西我可以整理或简化,这只是一个粗略的草案本身,一旦我的一切工作,我会清理。 我已经尝试了多种方法来获得正确设置的y值,最接近我最终画出一条直的对角线,它没有像它应该的那样弯曲。 我该怎么做才能正确设置y值,以便正确绘制[0,2pi]的sin图?

试图澄清问题:问题在于更改drawLine函数的y值。 基本上,我工作的东西不能正确地绘制sin函数,因为我只能想出以线性递增它。 它看起来像这样:

  /\ / \ / \/ 

我的最终问题是:我怎样才能使我的y坐标与sin(x)图的正确y坐标一起缩放? 换句话说,我怎样才能使它“不直”并且像sin(x)图一样适当弯曲。

另一种看待问题的方法是如何用我的JFrame像素正确“缩放”sin(x)的y值? 感谢您的时间,感谢您的帮助。

好吧,David Wallace在评论中提到你需要减少你的x增量,但我认为你试图在整个width间隔内得到2*PI

使用y = Math.sin(x*Math.PI*2/getWidth()); 这会在将x值插入sin函数之前对其进行缩放。

那么这里是代码,它不仅可以绘制sin(x)的图形,而且可以使用外部解析器绘制任何图形。

  import javax.swing.*; import java.awt.*; import java.util.Scanner; import net.objecthunter.exp4j.*; class math extends JFrame { public static void main(String args[]) { math m=new math(); m.setVisible(true); m.setLocationRelativeTo(null); } public void paintallies(Graphics G1,double sf) {int i; Graphics2D g21=(Graphics2D) G1; g21.setColor(Color.GREEN); for(i=0;i<=600;i=(int) (i+sf)) { g21.drawLine(i,0,i,600); g21.drawLine(0,i,600,i); } } public void paintaxes(Graphics G1) { Graphics2D g21=(Graphics2D) G1; g21.setColor(Color.BLACK); g21.drawLine(300,0,300,600);//y axis g21.drawLine(0,300,600,300); //x axis } public void paint(Graphics G) { int i; double j,k; Scanner s=new Scanner(System.in); System.out.println("Enter input"); String input=s.nextLine(); System.out.println("Enter scale factor"); double sf=s.nextDouble(); double sff=300/sf; double kf=sff; double count=0; Graphics g2=(Graphics) G; paintallies(G,sf); paintaxes(G); g2.translate(300,300); do { kf=kf-(1/sf); count++; }while(kf>=0); double counts=2*count; Color c=Color.RED; g2.setColor(c.darker()); double yarr[]=new double[(int)counts]; double xarr[]=new double[(int)counts]; Expression E=new ExpressionBuilder(input).variables("x").build(); j=-sff; k=-sff; for(i=0;i 

}