判断一个点是否在三角形内 java_判定一个点是否在三角形内(原)

publicclassCanvasPanelextendsJPanel {privatestaticfinallongserialVersionUID=-6665936180725885346L;privatePoint firstPoint=null;privatePoint secondPoint=null;privatePoint thirdPoint=null;publicCanvasPanel() {

setBackground(Color.WHITE);

addMouseListener(mouseAdapter);

addMouseMotionListener(mouseAdapter);

}publicvoidpaintComponent(Graphics g) {super.paintComponent(g);

drawTriangel(g);

}privatevoiddrawTriangel(Graphics g) {if(firstPoint!=null&&secondPoint!=null) {

g.drawLine(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y);if(thirdPoint!=null) {

g.drawLine(firstPoint.x, firstPoint.y, thirdPoint.x, thirdPoint.y);

g.drawLine(secondPoint.x, secondPoint.y, thirdPoint.x, thirdPoint.y);

}

}

}privatestaticbooleaninTriangle(Point pos, Point posA, Point posB,

Point posC) {doubletriangeArea=triangleArea(posA, posB, posC);doublearea=triangleArea(pos, posA, posB);

area+=triangleArea(pos, posA, posC);

area+=triangleArea(pos, posB, posC);doubleepsilon=0.0001;if(Math.abs(triangeArea-area)

}returnfalse;

}privatestaticdoubletriangleArea(Point pos1, Point pos2, Point pos3) {doubleresult=Math.abs((pos1.x*pos2.y+pos2.x*pos3.y+pos3.x*pos1.y-pos2.x*pos1.y-pos3.x*pos2.y-pos1.x*pos3.y)/2.0D);returnresult;

}privateMouseInputAdapter mouseAdapter=newMouseInputAdapter() {publicvoidmouseReleased(MouseEvent e) {

Point pos=e.getPoint();if(firstPoint==null) {

firstPoint=pos;

}elseif(secondPoint==null) {

secondPoint=pos;

Graphics g=CanvasPanel.this.getGraphics();

CanvasPanel.this.paintComponent(g);

g.drawLine(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y);

}elseif(thirdPoint==null) {

thirdPoint=pos;

Graphics g=CanvasPanel.this.getGraphics();

CanvasPanel.this.paintComponent(g);

g.drawLine(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y);

g.drawLine(firstPoint.x, firstPoint.y, thirdPoint.x, thirdPoint.y);

g.drawLine(secondPoint.x, secondPoint.y, thirdPoint.x, thirdPoint.y);

}

}publicvoidmouseMoved(MouseEvent e) {

Point pos=e.getPoint();

Graphics2D g2=(Graphics2D) CanvasPanel.this.getGraphics();

CanvasPanel.this.paintComponent(g2);if(firstPoint!=null&&secondPoint==null) {

g2.drawLine(firstPoint.x, firstPoint.y, pos.x, pos.y);

}elseif(firstPoint!=null&&secondPoint!=null&&thirdPoint==null) {

g2.drawLine(firstPoint.x, firstPoint.y, pos.x, pos.y);

g2.drawLine(secondPoint.x, secondPoint.y, pos.x, pos.y);

}elseif(firstPoint!=null&&secondPoint!=null&&thirdPoint!=null) {if(inTriangle(pos, firstPoint, secondPoint, thirdPoint)) {

g2.setColor(Color.RED);

}else{

g2.setColor(Color.BLUE);

}intradius=4;

g2.drawOval(pos.x-radius, pos.y-radius, radius*2, radius*2);

}

}

};

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值