Java examples for 2D Graphics:Rectangle
Do these two rectangles overlap horizontally?
// All rights reserved. //package com.java2s; import java.awt.*; public class Main { /**/*from ww w . j a v a 2s .c om*/ * Private utility method. Do these two rectangles overlap horizontally? <p> * NOTE: This method will still return true if the two rectangles are positioned * one above the other even though they don't completely overlap. */ private static boolean rectanglesOverlapping_XAxis(Rectangle rec1, Rectangle rec2) { boolean bOverlapping = false; if ((rec1 == null) || (rec2 == null)) { return false; } int nLeft1 = (int) (rec1.getX()); int nRight1 = (int) (rec1.getX()) + (int) (rec1.getWidth()); int nLeft2 = (int) (rec2.getX()); int nRight2 = (int) (rec2.getX()) + (int) (rec2.getWidth()); // Find the intersections. If two lines coming from a rectangle corner // both have intersection points then there IS overlap. boolean bLeft1_Intersects = false; boolean bRight1_Intersects = false; boolean bLeft2_Intersects = false; boolean bRight2_Intersects = false; // Are there intersections based on rectangle #1? if ((nLeft1 > nLeft2) && (nLeft1 < nRight2)) { bLeft1_Intersects = true; } if ((nRight1 > nLeft2) && (nRight1 < nRight2)) { bRight1_Intersects = true; } // Are there intersections based on rectangle #2? if ((nLeft2 > nLeft1) && (nLeft2 < nRight1)) { bLeft2_Intersects = true; } if ((nRight2 > nLeft1) && (nRight2 < nRight1)) { bRight2_Intersects = true; } // Do we overlap or not? if (bLeft1_Intersects || bLeft2_Intersects || bRight1_Intersects || bRight2_Intersects) { bOverlapping = true; } return bOverlapping; } }