要确保画出的圆弧按照P1->P2->P3的顺序,请给出JAVA语言的示例代码
时间: 2024-02-20 08:59:12 浏览: 83
好的,以下是一个示例代码,可以确保绘制的圆弧按照 P1 -> P2 -> P3 的顺序:
```java
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DrawArc extends JPanel {
private static final long serialVersionUID = 1L;
private Point p1, p2, p3;
public DrawArc(Point p1, Point p2, Point p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x1 = p1.x, y1 = p1.y;
int x2 = p2.x, y2 = p2.y;
int x3 = p3.x, y3 = p3.y;
// 计算圆心坐标
double ma = (y2 - y1) / (x2 - x1);
double mb = (y3 - y2) / (x3 - x2);
int centerX = (int) ((ma * mb * (y1 - y3) + mb * (x1 + x2) - ma * (x2 + x3)) / (2 * (mb - ma)));
int centerY = (int) (-1 * (centerX - (x1 + x2) / 2) / ma + (y1 + y2) / 2);
// 计算起始和结束角度
double angle1 = Math.atan2(y1 - centerY, x1 - centerX);
double angle2 = Math.atan2(y3 - centerY, x3 - centerX);
int startAngle = (int) Math.toDegrees(angle1);
int endAngle = (int) Math.toDegrees(angle2);
// 计算圆弧半径
double radius = Math.sqrt(Math.pow(x1 - centerX, 2) + Math.pow(y1 - centerY, 2));
// 绘制圆弧
g.drawArc(centerX - (int) radius, centerY - (int) radius, (int) (2 * radius), (int) (2 * radius), startAngle, endAngle - startAngle);
}
public static void main(String[] args) {
Point p1 = new Point(50, 50);
Point p2 = new Point(100, 100);
Point p3 = new Point(150, 50);
JFrame frame = new JFrame("DrawArc");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawArc panel = new DrawArc(p1, p2, p3);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
```
这个示例代码中,我们通过计算 P1、P2、P3 三个点的坐标来确定圆弧的圆心和半径,然后根据起始和结束角度绘制圆弧。同时,我们将绘制圆弧的逻辑封装在了 JPanel 的 paintComponent 方法中,这样可以方便地在 JFrame 中展示出来。最后,我们通过创建一个 JFrame 对象来显示圆弧。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)