【问题标题】:How to get that click is in the shape or outside the shap.如何获得点击是在形状或形状之外。
【发布时间】:2014-11-22 18:53:12
【问题描述】:

我需要让程序有一个三角形,当我点击三角形时消息框会显示“在三角形中”,如果点击外部则“在三角形之外”

有三角形代码和获取点击坐标。但我无法对上面提到的内容做出逻辑。

如果有更好的方法来绘制三角形,请告诉我。 或者如果这项工作在 matlab 中很容易,那么也建议我这样做。

类 1 绘制三角形

public class Triangle extends JComponent  
    {  
       public void paintComponent(Graphics g)  
        {  
            Graphics2D g2 = (Graphics2D) g;  
            g2.draw(new Line2D.Double (100, 100, 200, 100));  
            g2.draw(new Line2D.Double (100, 100, 150, 200));
            g2.draw(new Line2D.Double (150, 200, 200, 100));
                 }  
        }

2 类

public class Tri_Angle extends MouseAdapter {        
Tri_Angle(){
      addMouseListener(new MouseAdapter() { 
      public void mousePressed(MouseEvent me) { 
      int x= me.getX();
      int y=     me.getY();
      System.out.println("clicked at (" + x + ", " + y + ")");
      } 
    });
}


public static void main(String[] args) {
    Triangle component = new Triangle ();  
    JFrame frame = new JFrame ();         
    final int FRAME_WIDTH = 250;  
    final int FRAME_HEIGHT = 250;  
    frame.setSize (FRAME_WIDTH, FRAME_HEIGHT);         
      frame.addMouseListener(new MouseAdapter() { 
      public void mousePressed(MouseEvent me) { 
         int x= me.getX();
         int y= me.getY();
         System.out.println("clicked at (" + x + ", " + y + ")");
      } 
    });
    frame.setTitle("A Test Frame");  
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
    frame.setVisible(true);  
    frame.add(component); 
}

【问题讨论】:

    标签: java matlab logic


    【解决方案1】:

    这很简单。

    • 取三角形顶点:p1(100, 100), p2(200, 100), p3(150, 200);
    • 为每条线恢复线方程;
    • 对于点击坐标和对面线函数的每个三角形顶点符号应该相同。

    Java 代码:

    public class Point {
        public final double x;
        public final double y;
        ...
    }
    
    // -1 - point is "below" line, 0 - point is on line, +1 - point is "above" line
    private int getPointPosition(Point p, Point p1, Point p2) {
        // Line equation: (p.x - p1.x) / (p1.x - p2.x) - (p.y - p1.y) / (p1.y - p2.y)) = 0
        // Canonical form: F = Ax + By + C
        return Double.sign((p.x - p1.x) * (p1.y - p2.y) - (p.y - p1.y) * (p1.x - p2.x));
    }
    
    private boolean isInTriangle(Point p, Point p1, Point p2, Point p3) {
        return getPointPosition(p, p1, p2) == getPointPosition(p3, p1, p2) &&
            getPointPosition(p, p1, p3) == getPointPosition(p2, p1, p3) &&
            getPointPosition(p, p2, p3) == getPointPosition(p1, p2, p3);
    }
    

    为了更好地理解这个数学,您可以在纸上画一幅图并玩弄方程式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      相关资源
      最近更新 更多