Java中绘制sin曲线
时间: 2024-06-10 21:05:33 浏览: 8
我们可以使用Java中的Graphics类和Math类来绘制sin曲线。以下是示例代码:
```java
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SinCurve extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 设置绘图区域大小和坐标轴基准线
int width = getWidth();
int height = getHeight();
int xAxis = height / 2;
int yAxis = width / 2;
// 绘制坐标轴
g.drawLine(0, xAxis, width, xAxis);
g.drawLine(yAxis, 0, yAxis, height);
// 绘制sin曲线
g.translate(yAxis, xAxis);
double scaleFactor = 50;
int xPrev = -yAxis;
int yPrev = xAxis;
for (int x = -yAxis; x <= yAxis; x++) {
double angle = Math.toRadians(x / scaleFactor);
int y = (int) (Math.sin(angle) * scaleFactor);
g.drawLine(xPrev, yPrev, x, -y);
xPrev = x;
yPrev = -y;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new SinCurve());
frame.setSize(600, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
运行这段代码将会显示一个窗口,其中绘制了一条sin曲线。具体的实现过程可参考注释。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)