java - 如何计算 5 点多边形中的点

标签 java swing

我有一个带有按钮的类演示,当用户单击名为“多边形”的按钮时,将从点击的点开始绘制多边形,该代码在绘图中工作正常,但不幸的是它在错误的位置绘制了多边形。

PolygonShape 类

class PolygonShape {

   int x, y;
   private Polygon p;

   public PolygonShape(int x, int y) {
    // the x, y sent to this constructor
    //are the cordinates of the point where the user clicked
    this.x = x;
    this.y = y;       
   }

   public void draw(Graphics g) {       
    p = new Polygon();
    for (int i = 0; i < 5; i++)
      p.addPoint((int) (x + y * Math.cos(i * 2 * Math.PI / 5)),
          (int) (x + y * Math.sin(i * 2 * Math.PI / 5)));
    g.drawPolygon(p);       
   }
}  

最佳答案

假设xy是多边形的中心,你使用它们是错误的(你需要将x添加到x坐标和 y 坐标),并且您缺少另一个重要变量:半径的 r 。您应该在公式中乘以 r,而不是乘以 y

换句话说:

class PolygonShape {

    int x, y, r;
    private Polygon p;

    public PolygonShape(int x, int y, int r) {
        this.x = x;
        this.y = y;
        this.r = r;       
    }

    // Provide a default radius of 100 pixels if no radius is given.
    public PolygonShape(int x, int y) {
        this(x, y, 100);
    }

    public void draw(Graphics g) {       
        p = new Polygon();
        for (int i = 0; i < 5; i++) {
            double angle = i * 2 * Math.PI / 5;
            p.addPoint((int) (x + r * Math.cos(angle)),
                       (int) (y + r * Math.sin(angle)));
        }
        g.drawPolygon(p); 
    }
} 

关于java - 如何计算 5 点多边形中的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26734515/

相关文章:

java - 循环结束,但没有结束

java - 如何在 Eclipse 的项目中包含 .class 文件? ( java )

java - System.out.print ('\r' ) 不起作用

java - 在不停用窗口的情况下捕获 JFrame 中的所有事件

java - 按键绑定(bind)没有响应

java - swing - 组件的短时间突出显示

java - JComboBox 未从 Hashtable 和 ArrayList 填充

java - 在 JTextPane 中逐行读取文本

java.lang.OutOfMemoryError : Java heap space with Htmlunit use 错误

java - 加载和显示大文本文件