How can I draw a rectangle towards the top of the application in java

user1035654 picture user1035654 · Sep 20, 2012 · Viewed 9.8k times · Source

How can I draw a rectangle towards the top of the application in java ? Normally the drawRect method draws towards the bottom I tried to use a negative number but this would not work

Graphics g = p.getGraphics();
g.fillRect(50, 200,50,100);

Answer

Zoe picture Zoe · Sep 20, 2012

In rectangles, the X and Y coordinates represent the top left corner. The length and width then draw away from the defining point. Your example draws a rectangle with the top left corner at 50,200 and with a width of 50 and a hight of 100, both away from those points in a positive direction. If you wanted a rectangle with 50,200 representing the lower left corner, simply subtract the height from that y coordinate (200), and use that as the starting y:

Graphics g = p.getGraphics();
g.fillRect(50, 100, 50, 100);

To address your examples, try something like this (I'll just use rectangle objects rather than actually filling the graphics):

int baseline = 200;
Rectangle rect1 = new Rectangle(50, baseline - 100, 50, 100);
Rectangle rect2 = new Rectangle(150, baseline - 50, 50, 50);
Rectangle rect3 = new Rectangle(250, baseline - 80, 50, 80);

After filling rectangles with these dimensions on the graphics object, you'll have three rectangles with a width of 50 each, spaced 50 apart, with the bottom all on the y=200 line.