-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDrawing.java
More file actions
59 lines (48 loc) · 2.03 KB
/
Drawing.java
File metadata and controls
59 lines (48 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import javax.swing.*;
import java.awt.*;
public class Drawing extends JPanel {
// 重写绘图方法
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.WHITE); // 设置背景色为白色
// 1. 绘制正弦曲线
g.setColor(Color.RED); // 设置画笔颜色为红色
int width = getWidth();
int height = getHeight();
int centerY = height / 2; // Y轴中心点
// 绘制坐标轴
g.drawLine(50, centerY, width - 50, centerY); // X轴
g.drawLine(50, 50, 50, height - 50); // Y轴
// 绘制正弦曲线(从x=50到x=width-50)
for (int x = 50; x < width - 50; x++) {
// 计算角度(将x坐标映射到0~2π)
double angle = (x - 50) * 2 * Math.PI / (width - 100);
// 计算正弦值,并映射到屏幕坐标
int y = centerY - (int)(Math.sin(angle) * 100);
// 绘制点(用小线段代替点,使曲线更清晰)
if (x > 50) {
g.drawLine(x - 1, prevY, x, y);
}
prevY = y;
}
// 2. 绘制基本几何图形
g.setColor(Color.BLUE); // 蓝色
g.drawRect(100, 100, 80, 50); // 矩形
g.setColor(Color.GREEN); // 绿色
g.fillOval(250, 100, 60, 60); // 填充圆形
g.setColor(Color.ORANGE); // 橙色
int[] xPoints = {400, 450, 350};
int[] yPoints = {130, 180, 180};
g.fillPolygon(xPoints, yPoints, 3); // 填充三角形
}
private int prevY; // 用于绘制曲线的辅助变量
public static void main(String[] args) {
// 创建窗口
JFrame frame = new JFrame("简单绘图示例");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400); // 窗口大小
frame.add(new Drawing()); // 添加绘图面板
frame.setVisible(true); // 显示窗口
}
}