Jfreechart:可以更改条形颜色吗?

问题描述:

是否可以更改条形颜色?

Is it possible to change the bar color?

我已经编写了一个简单的计数程序.

I have coded a simple program for counting.

我还想实现一件事:如果计数大于200,请使用蓝色绘制该条.如果不是,请使用黄色.

I want to implement one more thing: if the count number is greater than 200, use blue color to draw the bar. If not, use yellow color to do so.

当前,所有条形颜色均为红色.

Currently, all bar color is in red.

所以,我想问一下,是否可以更改条形颜色?

So, I would like to ask, is it possible to change the bar color?

如果是,有人可以给我一些指导来实现吗?

If yes, can someone give me some guide to realize?

提前谢谢!

附上我的编码:

<%@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>

魔术是 BarRenderer类.

一个例子是在 http ://javabeanz.wordpress.com/2007/07/04/creating-barcharts-with-custom-colours-using-jfreechart/

您要尝试执行的操作类似于:

What you're trying to do would be something like:

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之后,进行

And then after your call to ChartFactory.createBarChart, you do

final CategoryPlot plot = chart.getCategoryPlot();
CategoryItemRenderer renderer = new CustomRenderer();
plot.setRenderer(renderer);