java 生成一个一直循环的正弦曲线
时间: 2023-07-04 21:13:32 浏览: 43
好的,我可以为您提供一个Java程序,它可以生成一个一直循环的正弦曲线。这个程序使用Java Swing绘制一个正弦曲线,然后使用一个线程来不断更新曲线的位置,从而让它看起来像是一直循环。请注意,这只是一个基本的代码示例,还需要根据您的具体需求进行修改:
```java
import java.awt.*;
import javax.swing.*;
public class SineWave extends JPanel implements Runnable {
private static final int W = 640;
private static final int H = 480;
private static final int PAD = 20;
private static final int MAX_X = 360;
private static final double MAX_Y = 1.0;
private static final int MIN_X = 0;
private static final double MIN_Y = -1.0;
private static final int TICK = 25;
private static final int POINTS = MAX_X - MIN_X + 1;
private double[] sin = new double[POINTS];
private int[] x = new int[POINTS];
private int[] y = new int[POINTS];
private int dx = 1;
public SineWave() {
for (int i = 0; i < POINTS; i++) {
x[i] = PAD + i;
sin[i] = Math.sin(Math.toRadians(i));
y[i] = (int) (H / 2 - sin[i] * H / 2);
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.drawPolyline(x, y, POINTS);
g2.setPaint(Color.red);
for (int i = 0; i < POINTS; i += TICK) {
int x0 = x[i];
int y0 = y[i];
g2.drawLine(x0, y0 - 4, x0, y0 + 4);
g2.drawString(String.valueOf(i), x0 - 6, y0 + 16);
}
g2.drawLine(PAD, H / 2, W - PAD, H / 2);
g2.drawLine(PAD, PAD, PAD, H - PAD);
}
public Dimension getPreferredSize() {
return new Dimension(W, H);
}
public void run() {
while (true) {
for (int i = 0; i < POINTS; i++) {
x[i] += dx;
y[i] = (int) (H / 2 - sin[(i + dx) % POINTS] * H / 2);
}
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SineWave wave = new SineWave();
f.add(wave);
f.pack();
f.setVisible(true);
Thread t = new Thread(wave);
t.start();
}
}
```
这个程序使用一个while循环和一个线程来不断更新曲线的位置。它将曲线向右移动一个像素,然后重新计算曲线上每个点的Y坐标。当曲线的最右侧到达屏幕的边缘时,它会重新从左侧开始绘制。希望这个代码对您有所帮助!