用java代码写一个钟摆程序
时间: 2023-04-08 09:03:32 浏览: 85
好的,以下是一个简单的Java钟摆程序:
```
import java.awt.*;
import javax.swing.*;
public class Clock extends JPanel {
private int angle = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int x = getWidth() / 2;
int y = getHeight() / 2;
int r = Math.min(x, y) - 2;
g2d.setStroke(new BasicStroke(2));
g2d.setColor(Color.BLACK);
g2d.drawOval(x - r, y - r, 2 * r, 2 * r);
int x1 = (int) (x + r * Math.sin(Math.toRadians(angle)));
int y1 = (int) (y - r * Math.cos(Math.toRadians(angle)));
g2d.drawLine(x, y, x1, y1);
}
public void setAngle(int angle) {
this.angle = angle;
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Clock");
Clock clock = new Clock();
frame.add(clock);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int angle = 0;
while (true) {
clock.setAngle(angle);
angle = (angle + 1) % 360;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这个程序使用Java Swing库绘制一个钟摆。它在一个无限循环中不断更新钟摆的角度,以模拟钟摆的运动。