我收到了一项任务并且能够完成它,但我觉得必须有一种更简单的方法来完成它。
我的任务是绘制 60 个宽度为 5、高度随机的垂直条。
public void paintComponent( Graphics g )
{
super.paintComponent( g );
g.setColor( color );
int width = getWidth();
int height = getHeight();
int x, h;
// bar with a width of 5 and random heights
h = rd.nextInt(height); //random height
x = 50;
g.drawLine( x, height, x, height-h ); //Bar 1
g.drawLine( x+1, height, x+1, height-h );
g.drawLine( x+2, height, x+2, height-h );
g.drawLine( x+3, height, x+3, height-h );
g.drawLine( x+4, height, x+4, height-h );
g.drawLine( x+6, height, x+6, height-h -12 ); // Bar 2
g.drawLine( x+7, height, x+7, height-h -12 );
g.drawLine( x+8, height, x+8, height-h -12 );
g.drawLine( x+9, height, x+9, height-h -12 );
g.drawLine( x+10, height, x+10, height-h -12);
我所做的只是对所有 60 个小节重复此操作,然后更改 height-h +/- * 末尾的偏移量,并在小节之间留出 1 的空格
这似乎是一个很长的路要走。关于如何实现这一点而不重复 60 次的任何建议。
编辑:添加了最终项目的图像。 这是最终的外观![1]
[1]: <a href="/image/3ivpM.png" rel="noreferrer noopener nofollow">/image/3ivpM.png</a>
最佳答案
看看其他答案,没有人指出显而易见的事情: 要绘制 60 个条形,您不需要绘制超过 60 个项目(当然不是 60x5=300 条线)。
您的选择:
- 将条形绘制为填充矩形
- 将条形绘制为宽度为 5 的线条
此外,绘制时不应计算条形值,它们应该是数据模型。
public class Bars extends JPanel {
private double[] barValues;
private final static int BAR_WIDTH = 5;
private final static int BAR_GAP = 3;
public Bars () {
barValues = new double[60];
for (int i = 0; i < barValues.length; i++) {
barValues[i] = Math.random();
}
}
...
}
使用矩形绘画:
@Override
protected void paintComponent (Graphics g) {
Dimension size = getSize();
g.setColor(Color.white);
g.fillRect(0, 0, size.width, size.height);
g.setColor(new Color(0x445566));
for (int i = 0; i < barValues.length; i++) {
int h = (int) Math.round(barValues[i] * size.height);
int x = (i * (BAR_WIDTH + BAR_GAP));
int y = size.height - 1 - h;
int w = BAR_WIDTH;
g.fillRect(x, y, w, h);
}
}
使用宽度为 5 的线条进行绘画:
@Override
protected void paintComponent (Graphics g) {
Dimension size = getSize();
g.setColor(Color.white);
g.fillRect(0, 0, size.width, size.height);
g.setColor(new Color(0x445566));
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(5, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER));
for (int i = 0; i < barValues.length; i++) {
int h = (int) Math.round(barValues[i] * size.height);
int x = (i * (BAR_WIDTH + BAR_GAP)) + BAR_WIDTH / 2;
int y = size.height - 1 - h;
g.drawLine(x, y, x, y + h);
}
}
关于java - 重复drawLine()来绘制垂直条Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20036335/