java 创建一个BarChat对象
时间: 2023-10-22 20:31:37 浏览: 37
好的,以下是使用Java语言创建一个简单的BarChart对象的示例代码:
```java
import javax.swing.*;
import java.awt.*;
public class BarChart extends JPanel {
private int[] values;
private String[] labels;
private Color[] colors;
public BarChart(int[] values, String[] labels, Color[] colors) {
this.values = values;
this.labels = labels;
this.colors = colors;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (values == null || values.length == 0) {
return;
}
int minValue = 0;
int maxValue = 0;
for (int i = 0; i < values.length; i++) {
if (minValue > values[i]) {
minValue = values[i];
}
if (maxValue < values[i]) {
maxValue = values[i];
}
}
Dimension dim = getSize();
int clientWidth = dim.width;
int clientHeight = dim.height;
int barWidth = clientWidth / values.length;
Font titleFont = new Font("SansSerif", Font.BOLD, 20);
FontMetrics titleFontMetrics = g.getFontMetrics(titleFont);
Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
FontMetrics labelFontMetrics = g.getFontMetrics(labelFont);
int titleWidth = titleFontMetrics.stringWidth("Bar Chart");
int y = titleFontMetrics.getAscent();
int x = (clientWidth - titleWidth) / 2;
g.setFont(titleFont);
g.drawString("Bar Chart", x, y);
int top = titleFontMetrics.getHeight();
int bottom = labelFontMetrics.getHeight();
double scale = (double) (clientHeight - top - bottom) / (double) (maxValue - minValue);
y = clientHeight - labelFontMetrics.getDescent();
g.setFont(labelFont);
for (int i = 0; i < values.length; i++) {
int valueX = i * barWidth + 1;
int valueY = top;
int height = (int) (values[i] * scale);
if (values[i] >= 0) {
valueY += (int) ((maxValue - values[i]) * scale);
} else {
valueY += (int) (maxValue * scale);
height = -height;
}
g.setColor(colors[i % colors.length]);
g.fillRect(valueX, valueY, barWidth - 2, height);
g.setColor(Color.black);
g.drawRect(valueX, valueY, barWidth - 2, height);
int labelWidth = labelFontMetrics.stringWidth(labels[i]);
x = i * barWidth + (barWidth - labelWidth) / 2;
g.drawString(labels[i], x, y);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bar Chart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int[] values = {5, 10, 15, 20, 25};
String[] labels = {"A", "B", "C", "D", "E"};
Color[] colors = {Color.red, Color.green, Color.blue, Color.yellow, Color.orange};
BarChart chart = new BarChart(values, labels, colors);
frame.getContentPane().add(chart);
frame.pack();
frame.setVisible(true);
}
}
```
这个示例代码创建了一个简单的BarChart对象,并显示在一个JFrame窗口中。你可以根据自己的需要修改values、labels和colors数组中的数据,以及更改窗口的标题、大小等属性。