java jfreechart里我用了barrenderer.setSeriesPaint,为啥柱子的颜色改变不了?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java jfreechart里我用了barrenderer.setSeriesPaint,为啥柱子的颜色改变不了?相关的知识,希望对你有一定的参考价值。

显示的统计图是这样的,我想把红蓝改成别的颜色

参考技术A

追问

怎么弄的啊?

参考技术B 别截图。上代码追问

代码太长,盛不下

数据库中jfreechart中的散点图

【中文标题】数据库中jfreechart中的散点图【英文标题】:scatter plot in jfreechart from database 【发布时间】:2014-07-06 01:20:55 【问题描述】:

如何在 java 中使用 jfreechart 在 mysql 数据库表中绘制数据散点图。我用过swing库。 任何链接都会有所帮助。我搜索了谷歌,但找不到一个可以理解的解决方案。 如果您有代码,请提供给我。 实际上我确实做了条形图并使用 jfreechart 绘制它。 我用于条形图的代码在这里。这里 display3 函数显示条形图。 如何修改它以显示散点图?

public void display3() throws SQLException, ClassNotFoundException

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    String JDBC_DRIVER="com.mysql.jdbc.Driver";
    String DB_URL="jdbc:mysql://localhost/data2";
    Connection conn;
    Statement stmt;
    String USER = "root";
    String PASS = "";
    try
        Class.forName(JDBC_DRIVER);
        conn=DriverManager.getConnection(DB_URL,USER,PASS);
        System.out.println("Creating statement...");
        stmt = conn.createStatement();

        String sql;
        sql="SELECT * FROM `production` WHERE crop_id = 1 AND location_id = 1";
        ResultSet rs=stmt.executeQuery(sql);

        while (rs.next())
            //String student = rs.getString("studentname");
            String yeartext = rs.getString("year_of_production");
            //double value = Double.parseDouble(text);
            String productiontext = rs.getString("production_amount");
            double production = Double.parseDouble(productiontext);
            Integer year = Integer.parseInt(yeartext);

            dataset.setValue(production, "production", year);


        



        JFreeChart chart = ChartFactory.createBarChart("Bar Graph",// Chart Title
                "Year", //horizontal axis label
                "Paddy Production", // vertical axis label
                dataset, //data
                PlotOrientation.VERTICAL, //orientation of chart
                true, //include legend
                false, // tool tips
                true);//urls
        CategoryPlot p = chart.getCategoryPlot();
        ChartPanel chartPanel = new ChartPanel(chart, false);
        jPanel9.setLayout(new BorderLayout());
        jPanel9.add(chartPanel, BorderLayout.EAST);
        jPanel9.add(chartPanel);
        SwingUtilities.updateComponentTreeUI(this);
        p.setRangeGridlinePaint(blue);

        System.out.println("Database created successfully...");

     catch(SQLException se) 
        //Handle errors for JDBC
        System.out.println("Connect failed ! ");
        se.printStackTrace();
    

       

  I finally solved my problem: 

优化代码如下,它可以工作:

public void display3() throws SQLException, ClassNotFoundException

        //DefaultCategoryDataset dataset = new DefaultCategoryDataset();
         XYSeriesCollection dataset = new XYSeriesCollection();
         XYSeries series = new XYSeries("production");
        String JDBC_DRIVER="com.mysql.jdbc.Driver";
    String DB_URL="jdbc:mysql://localhost/data2";
    Connection conn;
    Statement stmt;
    String USER = "root";
    String PASS = "";
        try
            Class.forName(JDBC_DRIVER);
            conn=DriverManager.getConnection(DB_URL,USER,PASS);
            System.out.println("Creating statement...");
            stmt = conn.createStatement();
                        String sql;
                        sql="SELECT * FROM `production` WHERE crop_id = 1 AND location_id = 1";
                        ResultSet rs=stmt.executeQuery(sql);

                        while (rs.next())
                            //String student = rs.getString("studentname");
                            String yeartext = rs.getString("year_of_production");
                            //double value = Double.parseDouble(text);
                            String productiontext = rs.getString("production_amount");
                            double production = Double.parseDouble(productiontext);
                            double year = Double.parseDouble(yeartext);
                            series.add(year,production) ;
                            //dataset.addSeries(series);




                        
                        dataset.addSeries(series);

                        JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot","Year","Paddy Production", dataset);

                        //CategoryPlot p = chart.getCategoryPlot();
                         //XYPlot xyplot = (XYPlot)jfreechart.getPlot();
                        //http://***.com/questions/12417732/jfreechart-with-scroller
                        ChartPanel chartPanel = new ChartPanel(chart, false);
                        jPanel9.setLayout(new BorderLayout());
                        jPanel9.add(chartPanel, BorderLayout.EAST);
                        jPanel9.add(chartPanel);
                        SwingUtilities.updateComponentTreeUI(this);
                       // p.setRangeGridlinePaint(blue);

                        System.out.println("Database created successfully...");

                catch(SQLException se)
                    //Handle errors for JDBC
                    System.out.println("Connect failed ! ");
                    se.printStackTrace();
//                    JOptionPane.showMessageDialog(MajorUI.this, err.getMessage());
                    

    

输出是: http://i58.tinypic.com/29ynsxh.png

【问题讨论】:

您可能会更多地利用方法。制作类似createChart(ResultSet rs) 的东西。你的代码有点疯狂。 这里有一个散点图的例子java2s.com/Code/Java/Chart/JFreeChartFastScatterPlotDemo.htm 【参考方案1】:

这个完整的示例在内存中创建了一个合适的数据库表,将其查询到 JDBCXYDataset 并在散点图中显示数据集。请注意第一列如何成为域,而连续的列成为单独的系列。

import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Random;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.jdbc.JDBCXYDataset;

/**
 * @see http://***.com/a/24592754/230513
 */
public class JDBCTest 

    private static final int N = 30;
    private static final Random r = new Random();

    private void display() 
        JFrame f = new JFrame("JDBCTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JDBCXYDataset jds = createDataset();
        JFreeChart chart = ChartFactory.createScatterPlot("Inventory",
            "Date", "Count", jds, PlotOrientation.VERTICAL, true, true, false);
        XYPlot plot = chart.getXYPlot();
        plot.setDomainAxis(new DateAxis("Date"));
        f.add(new ChartPanel(chart));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        for (int i = 0; i < jds.getItemCount(); i++) 
            System.out.println(new Date(jds.getX(0, i).longValue()));
        
    

    private JDBCXYDataset createDataset() 
        try 
            Connection conn = DriverManager.getConnection(
                "jdbc:h2:mem:test", "", "");
            Statement st = conn.createStatement();
            st.execute("create table inventory(when date, n1 integer, n2 integer)");
            PreparedStatement ps = conn.prepareStatement(
                "insert into inventory values (?, ?, ?)");
            Calendar c = Calendar.getInstance();
            for (int i = 0; i < N; i++) 
                ps.setDate(1, new Date(c.getTimeInMillis()));
                ps.setInt(2, N / 3 + r.nextInt(N / 3));
                ps.setInt(3, N / 2 + r.nextInt(N / 3));
                ps.execute();
                c.add(Calendar.MONTH, 1);
            
            JDBCXYDataset jds = new JDBCXYDataset(conn);
            jds.executeQuery("select when, n1, n2 from inventory");
            return jds;
         catch (SQLException ex) 
            ex.printStackTrace(System.err);
        
        return null;
    

    public static void main(String[] args) 
        EventQueue.invokeLater(new Runnable() 
            @Override
            public void run() 
                new JDBCTest().display();
            
        );
    

【讨论】:

以上是关于java jfreechart里我用了barrenderer.setSeriesPaint,为啥柱子的颜色改变不了?的主要内容,如果未能解决你的问题,请参考以下文章

英语美文:Barren Spring (赛珍珠《贫瘠的春天》)(中英文)

JFreeChart - Java 内存泄漏

在项目里我用jquery进行ajax请求服务器 服务器返回的不是json而是html代码

Java 报表之JFreeChart(第二讲)

JFreeChart 之折线图

JFreeChart 之柱状图