Search code examples
javamouselistenertriangular

how to get mouselistener notice clicks inside an imaginary triangle?


I have three points on a grid. I want my mouselistener to give me a heads up, when a point on the area within this imaginary triangle of three points has been clicked. how to do that??I dont wanna use a shape class or anything, since it is an imaginary triangle. any ideas ? thx!


Solution

  • The following code should accomplish what you're trying to do.

    private static final Polygon POLY = new Polygon();
    
    static {
        POLY.addPoint(x1, y1); // first point
        POLY.addPoint(x2, y2); // second point
        POLY.addPoint(x3, y3); // third point
    }
    
    @Override
    public void mouseClicked(final MouseEvent e) {
        if (POLY.contains(e.getX(), e.getY())) {
            // notify user
        }
    }
    

    Note that you need to have some sort of polygon defined even though the triangle you have is "imaginary." This is so Java knows what sort of points could be inside the shape.