gpt4 book ai didi

java - 来自数据库的 JFreeChart 条形图数据集

转载 作者:行者123 更新时间:2023-12-01 13:33:20 24 4
gpt4 key购买 nike

我的目标是生成this Bar Chart使用 JFreeChart。

我正在尝试使用 MVC 从数据库获取 JFreeChart 数据; Bean、数据访问对象 (DAO) 和 Servlet。我在 Servlet 中编写代码时遇到问题。以下代码是我到目前为止所拥有的。

非常感谢您的帮助,并提前感谢您! :)

数据库

id |收入

<小时/>

R1 | 999
M3 | 832
G7 |第318章

bean

public class Revenue
{
private String id;
private Integer revenue;

//getters and setters
}

DAO

public ArrayList<Revenue> getAllRevenueList()
{
try
{
//driver
//connection code

String sql = "SELECT id,revenue FROM revenue_table";
Statement stmt = con.createStatemtnt();
ResultSet rs = stmt.executeQuery(sql);

ArrayList<Revenue> revenueList = new ArrayList<Revenue>();
while(rs.next)
{
Revenue r = new Revenue();
r.setId(rs.getString("id"));
r.setRevenue(Integer.parseInt(rs.getString("revenue")));
revenueList.add(r); //add object to list
}

return revenueList;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}

Servlet

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.setContentType("image/png");

OutputStream outputStream = response.getOutputStream();
JFreeChart chart = getRevenueChart();

int width = 1100;
int height = 350;
ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);


}

public JFreeChart getRevenueChart() {

//Cannot instantiate the type CategoryDataset

CategoryDataset dataset = new CategoryDataset();

ArrayList<Bean> revenueList = DAO.getAllRevenueList();

if (revenueList != null && !revenueList.isEmpty()) {
for (Bean r : revenueList) {
dataset.setValue(r.getRevenue(), r.getID());

}
}

JFreeChart chart = ChartFactory.createBarChart3D("Graph Title",
"ID",
"Revenue",
dataset,
PlotOrientation.VERTICAL,
false,
false,
false);

CategoryPlot plot = chart.getCategoryPlot();
CategoryAxis axis = plot.getDomainAxis();

CategoryItemRenderer renderer = plot.getRenderer();
BarRenderer r = (BarRenderer) renderer;
r.setMaximumBarWidth(0.95);

return chart;
}

最佳答案

如果您的问题是从给定的 List<Revenue> 创建图表然后尝试类似以下的操作。

DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (Revenue revenue : revenueList) {
// the middle parameter is for naming the value, can be empty if you have just one
dataset.addValue(revenue.getRevenue(), "", revenue.getId());
}

JFreeChart chart = ChartFactory.createBarChart(
"",
"",
"Revenues",
dataset,
PlotOrientation.VERTICAL,
true,
false,
false
); // or whatever parameters you need

有关静态工厂方法的信息是 here .

关于java - 来自数据库的 JFreeChart 条形图数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21431658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com