Java: Paint a histogram via fillRect()

2019-01-29 09:41发布

问题:

I like to make a histogram. With drawLine(), it's not really a problem for me, but when I try to do it with fillRect() the rectangles are going from top to bottom. I would like to paint the histogram looking similar to my histogram with drawLine().

Here is my code:

public void paint(Graphics g) {

    super.paint(g); 
    int height = getHeight();
    int width = getWidth();
    int x =10;
    haufigkeit=model.getMap();
    for(int i = 1; i <= 45; i++) {
        int y;
        y = haufigkeit.get(i);            
        Color color = new Color(0, 0, (int)(150 + Math.random() * 100));
        g.setColor(color);

        // g.fillRect(x, 50, 10, y);

        // g.drawLine(x, height - 50, x, height- y);

        x+=20;
    }

}

What needs to be changed?

回答1:

"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);


回答2:

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.