可以更改条形颜色吗?
我已经编写了一个简单的计数程序。
我要实现另一件事:如果计数大于200,请使用蓝色绘制该条。如果不是,请使用黄色。
当前,所有条形颜色均为红色。
因此,我想问一下,是否可以更改条形颜色?
如果是,有人可以给我一些指导来实现吗?
提前致谢!
附件是我的编码:
<%@page contentType="text/html"%>
<%@page import="java.io.*" %>
<%@page import="java.sql.*" %>
<%@page import="org.jfree.data.category.*" %>
<%@page import="org.jfree.chart.*" %>
<%@page import="org.jfree.chart.plot.*" %>
<html>
<body>
<%
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
try
{
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/delivery","root","root");
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery("SELECT inventory, subject from statistics");
int count;
String subject;
while (res.next())
{
count = res.getInt("inventory");
subject = res.getString("subject");
dataset.addValue(count,"enrollment count statistics", subject);
}
}
catch (Exception e) {
System.err.println(e.getMessage());
}
JFreeChart bar = ChartFactory.createBarChart("Enrollment Chart", "subject","Count",dataset, PlotOrientation.HORIZONTAL,true, false, false);
//BarRenderer renderer = (BarRenderer) bar.getCategoryPlot().getRenderer();
String fileName = "/bar.png";
String file = application.getRealPath("/") + fileName;
try
{
FileOutputStream fileOut = new FileOutputStream(file);
ChartUtilities.writeChartAsPNG(fileOut, bar, 300, 300);
}
catch (IOException e)
{
out.print(e);
}
%>
<img src="/delivery/bar.png" alt="subject Bar Chart" />
</body>
</html>
最佳答案
魔法是getItemPaint(int,int) method的BarRenderer class。
一个例子在http://javabeanz.wordpress.com/2007/07/04/creating-barcharts-with-custom-colours-using-jfreechart/
您要尝试执行的操作类似于:
class CustomRenderer extends BarRenderer
{
public CustomRenderer()
{
}
public Paint getItemPaint(final int row, final int column)
{
// returns color depending on y coordinate.
return (row > 200) ? Color.blue : Color.yellow ;
}
}
然后,在调用ChartFactory.createBarChart之后,执行
final CategoryPlot plot = chart.getCategoryPlot();
CategoryItemRenderer renderer = new CustomRenderer();
plot.setRenderer(renderer);