Checks if point px,py is within the bounds of the rectangle - Java 2D Graphics

Java examples for 2D Graphics:Rectangle

Description

Checks if point px,py is within the bounds of the rectangle

Demo Code

/*******************************************************************************
 * Copyright (c) 2011 MadRobot./* w w  w .  ja  v a 2  s .c o m*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *  Elton Kent - initial API and implementation
 ******************************************************************************/
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        float px = 2.45678f;
        float py = 2.45678f;
        float x = 2.45678f;
        int y = 2;
        int width = 2;
        int height = 2;
        System.out.println(withinBounds(px, py, x, y, width, height));
    }

    /**
     * Checks if point px,py is within the bounds of the rectangle
     * 
     * @param px
     *            x coordinate of the point to be checked
     * @param py
     *            y coordinate of the point to be checked
     * @param x
     *            point of the rectangle
     * @param y
     *            point of the rectangle
     * @param width
     *            of the rectangle
     * @param height
     *            of the rectangle
     * @return
     */
    public static boolean withinBounds(final float px, final float py,
            final float x, final int y, int width, int height) {
        if ((width | height) < 0) {
            return false;
        }
        if ((px < x) || (py < y)) {
            return false;
        } else {
            width += x;
            height += y;
            return ((width < x) || (width > px))
                    && ((height < y) || (height > py));
        }
    }
}

Related Tutorials