Java 如何在形状内或形状外单击。
我需要使该程序有一个三角形,当我点击在三角形消息框将显示“在三角形”和如果点击外,然后“在三角形外” 有三角形的代码,可以得到点击坐标。但我无法解释上面提到的逻辑 如果有更好的方法画三角形,那就告诉我。 或者,如果这项工作在matlab中很容易,那么建议我也这样做 类1绘制三角形Java 如何在形状内或形状外单击。,java,matlab,logic,Java,Matlab,Logic,我需要使该程序有一个三角形,当我点击在三角形消息框将显示“在三角形”和如果点击外,然后“在三角形外” 有三角形的代码,可以得到点击坐标。但我无法解释上面提到的逻辑 如果有更好的方法画三角形,那就告诉我。 或者,如果这项工作在matlab中很容易,那么建议我也这样做 类1绘制三角形 public class Triangle extends JComponent { public void paintComponent(Graphics g) {
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);
}
这很简单
- 取三角形顶点:p1(100100),p2(200100),p3(150200)李>
- 恢复每条线路的线路方程李>
- 对于单击坐标和每个三角形顶点,相反直线函数的符号应相同
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);
}
为了更好地理解这个数学,你可以在纸上画一个图像,然后玩方程式