Java:通过fillRect()绘制直方图
我喜欢制作直方图.对于drawLine()
来说,这对我来说并不是真正的问题,但是当我尝试使用fillRect()
进行操作时,矩形会从上到下移动.我想用drawLine()
绘制类似于我的直方图的直方图.
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()
.
这是我的代码:
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;
}
}
需要更改什么?
但是当我尝试使用fillRect时,矩形从上到下."
"but when i try to do it with fillRect the Rectangles are going from top to bottom."
您需要考虑的几件事.
-
水平线,例如,如果面板尺寸为500,则您希望水平线为450.因此,我们从此开始
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;
您需要考虑每个数据栏的高度.为此,您需要一个增量,让每个单位说5 px.因此,要获得高度,请将单位数量乘以增量量
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;
现在您所要做的就是从horizon
中减去height
,您便有了y
的起点,而fillOval
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);