我喜欢制作直方图。使用drawLine()
,这对我来说并不是真正的问题,但是当我尝试使用fillRect()
时,矩形会从上到下移动。我想用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;
}
}
需要改变什么?
最佳答案
"but when i try to do it with fillRect the Rectangles are going from top to bottom."
您需要考虑的一些事项。
水平线,例如,如果您的面板尺寸为 500,您会希望水平线约为 450。所以让我们从它开始
int horizon = 450;
您需要考虑每个数据条的高度。为此,您需要一个增量,假设每个单位增量为 5 像素。因此,要获得高度,请将单位数乘以增量量
int increment = 5; ... int height = increment * units;
现在您需要做的就是从
地平线
中减去高度
,您就得到了y
的起点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);
关于Java:通过 fillRect() 绘制直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22361639/