0

Hello I am trying to paint a bar graph using g.fillRect() to make each bar.

The bars will start at the grid height, y: 700, and fill upwards to y: 350 for example.

I am unable to set a negative x-height for my bar:

public void paint(Graphics g) {
    for (Bar b : this.bars) {
        g.fillRect(b.x_location,b.y_location,b.width,b.height * (-1));
    }
}

This won't paint the bars.

Fix:

public void paint(Graphics g) {
    for (Bar b : this.bars) {
        g.fillRect(b.x_location,b.y_location - b.height,b.width,b.height);
    }
}
Jasoon
  • 15
  • 5
  • 2
    You can't, because of the way the API works, in extends down and to the right. Instead, subtract the distance from the `y` coordinate and maintain the height as a positive value – MadProgrammer Apr 29 '17 at 23:34
  • [For example](http://stackoverflow.com/questions/22645172/java-draws-rectangle-one-way-not-both/22645343#22645343) – MadProgrammer Apr 29 '17 at 23:36
  • This works, tyvm. I subtracted the height of the bar from our y-coordinate and it did just what it needed to do. – Jasoon Apr 29 '17 at 23:37

1 Answers1

1

You can't, because of the way the API works, it extends down and to the right. Instead, subtract the distance from the y coordinate and maintain the height as a positive value

From the JavaDocs

Fills the specified rectangle. The left and right edges of the rectangle are at x and x + width - 1. The top and bottom edges are at y and y + height - 1. The resulting rectangle covers an area width pixels wide by height pixels tall. The rectangle is filled using the graphics context's current color.

While not a direct duplicate, this example demonstrates the basic concepts

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366