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);
}
}
};
}