Java: Paint a histogram via fillRect()

可紊 提交于 2019-11-29 18:05:57

"but when i try to do it with fillRect the Rectangles are going from top to bottom."

A few things you need to consider.

  1. A horizon line, for example if your panel size is 500, you'll want the horizon line to be something like 450. So let's start with that

    int horizon = 450;
    
  2. You need to consider the height of each data bar. To do that you need an increment amount, lets just say for every unit, an increment of 5 px. So to get the height you multiply the number of units by the increment amount

    int increment = 5;
    ...
    int height = increment * units;
    
  3. Now all you need to do is subtract the height from the horizon and you have your y starting point for the fillOval

    int y = horizon - height
    

 0  +---------------------
    |
    |
    |
    |    +----+   horizon - height = 150 = y point for fillRect
    |    |    |
    |    |    |
    |    |    |
 y  |    |    |   height = 300
    |    |    |
    |    |    |
    |    |    |
    |----------------------  450 horizon
    |
    +----------------------  500

g.fillRect(x, y, width, height);

I would suggest rotate/translate the Graphics object:

Graphics2D graphics = (Graphics2D) g;
graphics.rotate(Math.PI, cx, cy);

where (cx, cy) is the centre of your drawing. Graphics will be rotated 180 degrees around that centre.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!