用Java绘制横的柱状图:读入5个数,每个数在1~15范围内,每个*代表一个数字,显示出柱状图
时间: 2024-03-18 17:40:16 浏览: 97
【JavaScript源代码】vue echarts实现横向柱状图.docx
以下是使用Java Swing绘制横向柱状图的示例代码:
```java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class HorizontalBarChart extends JFrame {
private static final long serialVersionUID = 1L;
private int[] data;
public HorizontalBarChart(int[] data) {
this.data = data;
setTitle("Horizontal Bar Chart");
setSize(500, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int barWidth = width / data.length;
int maxBarHeight = height - 50;
g.setColor(Color.BLUE);
for (int i = 0; i < data.length; i++) {
int barHeight = data[i] * maxBarHeight / 15;
int x = i * barWidth + 50;
int y = height - barHeight - 20;
g.drawString(String.valueOf(data[i]), x + 5, y - 5);
g.fillRect(x, y, barWidth - 10, barHeight);
}
}
};
panel.setPreferredSize(new Dimension(500, 300));
getContentPane().add(panel);
}
public static void main(String[] args) {
int[] data = { 5, 10, 2, 8, 12 };
HorizontalBarChart chart = new HorizontalBarChart(data);
chart.setVisible(true);
}
}
```
在这个示例中,我们使用了JPanel类来绘制柱状图。在paintComponent方法中,我们首先计算出每个柱子的宽度和高度,然后通过循环绘制出每个柱子,并在顶部标注该柱子的值。为了使柱状图更加美观,我们将柱子的颜色设置为蓝色。最后,我们将绘制好的柱状图添加到JFrame中并显示出来。
阅读全文