使用Java三角函数结合AWT库根据边角参数绘制三角形求助
实现方案
坐标计算逻辑
- 固定三角形第一个顶点A的坐标为
(300, 600)作为绘制基准,避免图形超出画布范围 - 将输入的已知边s1设为水平向右的边,因此第二个顶点B的坐标直接为
(300 + s1, 600) - 第三个顶点C的坐标通过极坐标转换计算:注意AWT画布的Y轴是向下增长的,因此垂直方向计算时需要对正弦值取反,公式如下:
C点x坐标 = 300 + s3 * Math.cos(Math.toRadians(a1)) C点y坐标 = 600 - s3 * Math.sin(Math.toRadians(a1))
代码修改说明
- 组件初始化时自动调用calc方法获取用户输入的三角形参数
- 修复原代码中三角函数计算时角度、弧度转换错误的问题
- 第三边计算改用正弦定理,简化逻辑降低计算误差
- 移除无返回值不生效的Math.toDegrees调用
完整可运行代码
import javax.swing.*; import java.awt.*; public class TriangleDrawProgram { public static void main (String[] args) { JFrame frame = new JFrame(); CustomPaintComponent c = new CustomPaintComponent(); frame.add(c); frame.setSize(1000,1000); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setTitle("Triangle"); frame.setVisible(true); } } class CustomPaintComponent extends Component { private Triangle triangle; // 构造组件时触发参数输入 public CustomPaintComponent() { triangle = calc(); } public void paint(Graphics g){ Graphics2D G2D = (Graphics2D)g; // 基准点A坐标 int ax = 300; int ay = 600; // 点B坐标,s1水平向右 int bx = (int) (ax + triangle.s1); int by = ay; // 点C坐标计算 int cx = (int) (ax + triangle.s3 * Math.cos(Math.toRadians(triangle.a1))); int cy = (int) (ay - triangle.s3 * Math.sin(Math.toRadians(triangle.a1))); int[] xpoints = {ax, bx, cx}; int[] ypoints = {ay, by, cy}; G2D.drawPolygon(xpoints, ypoints, 3); } public Triangle calc(){ double s1,a1,a2; s1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter side 1")); a1 = Integer.parseInt(JOptionPane.showInputDialog("Please enter angle 1")); a2 = Integer.parseInt(JOptionPane.showInputDialog("Please enter angle 2")); // 计算第三个角 double a3 = 180 - (a1 + a2); // 用正弦定理计算另外两条边,逻辑更简单 double sinA1 = Math.sin(Math.toRadians(a1)); double s2 = s1 * Math.sin(Math.toRadians(a2)) / sinA1; double s3 = s1 * Math.sin(Math.toRadians(a3)) / sinA1; System.out.println("side 1 is " + s1 + " side 2 is " + s2 + " side 3 is " + s3 + " and the third angle is: " + a3); return new Triangle(s1,s2,s3,a1,a2,a3); } } class Triangle{ double s1,s2,s3,a1,a2,a3; Triangle(double s1, double s2, double s3, double a1, double a2, double a3){ this.s1 = s1; this.s2 = s2; this.s3 = s3; this.a1 = a1; this.a2 = a2; this.a3 = a3; } }
使用说明
运行程序后依次输入第一条边的长度(建议输入200-400之间的值避免超出画布)、第一个角、第二个角即可自动绘制对应三角形。
内容的提问来源于stack exchange,提问作者Leon Fardell
相关产品推荐
相关产品推荐

