Как отобразить время, которое хранится в базе данных на Timseries Chart - PullRequest
1 голос
/ 03 апреля 2012

Я занимаюсь разработкой таблицы временных рядов с использованием библиотеки Jfree. Я храню время в базе данных. Я хочу отобразить это время на графике. Как я могу это сделать. У меня есть один товар таблицы, имеющий столбцы, такие как цена, объем, дата и время. Я строю график цены и объема из базы данных. Я хочу время, которое есть в базе данных, которое также должно быть нанесено на ось X. Прямо сейчас это дает мне случайные сроки. Я хочу, чтобы мое время базы данных. У меня есть таблица, в которой я храню время события. Поэтому я хочу отобразить это время по оси X на графике временных рядов.

Вот мой код

/*
 * commoditychart.java
 */
package com.das.dbmodule;

import com.das.dbmodule.Dbconnection;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYAreaRenderer;
import org.jfree.data.time.Hour;
import org.jfree.data.time.RegularTimePeriod;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Vector;
import javax.swing.*;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;

public class commoditychart {

    private static final String CHARTDIR = "";
    String theResult = "";

    public commoditychart() {
    }

    public String produceAllCharts(String cmname, String today, String imagepath)
        throws ClassNotFoundException, SQLException {
        int count = 4,
            i = 0,
            id = 2,
            x = 0;
        String str = cmname;
        String tsym = null,
            commodity = cmname,
            path = "";
        Vector allSyms = null;
        ResultSet results = null,
            results1 = null;
        JFrame frame = null;
        File ifle = null;
        String chartFilename = null;
        Dbconnection dbobject = new Dbconnection();
        System.out.println("In commodity");
        dbobject.Dbconnect();
        System.out.println("call con");

        String startingtime = "00:00:00";
        String endingtime = "23:59:59";

        tsym = str;

        try {
            System.out.println(" inside commodity ");
            results1 = dbobject.execSQL(""
                + "Select open_contract_vol, open_contract_price , Date, Time "
                + "from commodity where com_name='" + cmname
                + "' and Date='" + today
                + "' and Time between '" + startingtime
                + "'  and '" + endingtime + "'");

            // results1 = DbObject.execSQL(query);// here the query get executed and the Resultset is populated.
            int count1 = 0;
            while (results1.next()) {
                count1++;// count1 is having total number of records that were feteched from the query.
            }

            results1.first();
            System.out.println("count1  --- =  " + count1);
            if (count1 > 0) {
                float[] dPrice = new float[count1];
                float[] dVolume = new float[count1];
                java.util.Date[] oDateTime = new java.util.Date[count1];

                for (i = 0; i < count1; i++) {
                    dVolume[i] = results1.getFloat("open_contract_vol");
                    dPrice[i] = results1.getFloat("open_contract_price");
                    oDateTime[i] = results1.getDate("Date");
                    System.out.println("price ::" + dPrice[i] + " vol :: "
                        + dVolume[i] + " date :: " + oDateTime[i]);
                    results1.next();
                }

                XYDataset xDataSet = createPriceDataset(dPrice);
                XYDataset yDataSet = createVolumeDataset(dVolume);
                JFreeChart chart = createChart(xDataSet, yDataSet, dPrice, dVolume, today);
                ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

                // ifle = new File("d:\\javapractice/marketpoint/web/"+tsym+".png");
                File ifle2 = new File(imagepath + tsym + ".png");

                // path = ifle.getAbsolutePath();
                path = ifle2.getAbsolutePath();
                System.out.println("new path " + path);

                try {
                    ChartUtilities.saveChartAsPNG(ifle2, chart, 600, 500, info);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

                chartFilename = this.CHARTDIR + tsym + ".png";
                count++;
            }
        } catch (Exception oError) {
            System.out.println("Here is the error :" + oError.getMessage());
        }
        return path;
    }

    private XYDataset createPriceDataset(final float[] dPrice) {
        final TimeSeriesCollection dataset = new TimeSeriesCollection();
        final TimeSeries s1 = new TimeSeries("Price (US $)", Hour.class);

        // RegularTimePeriod start = new Minute();
        RegularTimePeriod start = new Hour();

        for (int i = 0; i < dPrice.length; i++) {
            s1.add(start, dPrice[i]);

            // System.out.println("time start is "+ start);
            start = start.next();
            start = start.next();
            start = start.next();
            start = start.next();
            start = start.next();
            start = start.next();
        }
        dataset.addSeries(s1);
        return dataset;
    }

    private JFreeChart createChart(XYDataset xDataSet, XYDataset yDataSet,
        final float[] dPrice, final float[] dVolume,
        String date) {

        // final XYDataset direction = createPriceDataset(600);
        // Date on which the chart is created
        final JFreeChart chart = ChartFactory.createTimeSeriesChart("Time", date,
            "Price(US $)", xDataSet, true, true, false);
        final XYPlot plot = chart.getXYPlot();

        plot.getDomainAxis().setLowerMargin(0.0);
        plot.getDomainAxis().setUpperMargin(0.0);

        float maxprice = 0;
        float maxvolume = 0;

        for (int j = 0; j < dPrice.length; j++) {
            if (dPrice[j] > maxprice) {
                maxprice = dPrice[j];
                // System.out.println("maxprice is "+ maxprice);
            }
        }

        for (int j = 0; j < dVolume.length; j++) {
            if (dVolume[j] > maxvolume) {
                maxvolume = dVolume[j];

                XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
                renderer.setSeriesLinesVisible(0, true);
                plot.setRenderer(renderer);
            }
        }

        final ValueAxis axis1 = new NumberAxis("Price(US $)");
        axis1.setRange(0.0, maxprice + 40);

        // add the wind force with a secondary dataset/renderer/axis
        plot.setRangeAxis(axis1);

        final XYAreaRenderer renderer2 = new XYAreaRenderer();
        final ValueAxis axis2 = new NumberAxis("Volume(Carton)");

        axis2.setRange(0.0, maxvolume + 40);
        renderer2.setSeriesPaint(0, new Color(0, 0, 255, 128));
        plot.setDataset(2, yDataSet);
        plot.setRenderer(2, renderer2);
        plot.setRangeAxis(2, axis2);
        plot.mapDatasetToRangeAxis(2, 2);
        chart.setBorderVisible(true);
        final DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("hh:mma"));
        return chart;
    }

    private XYDataset createVolumeDataset(float[] dVolume) {
        final TimeSeriesCollection dataset = new TimeSeriesCollection();
        final TimeSeries s1 = new TimeSeries("Volume(Carton) ", Hour.class);
        RegularTimePeriod start = new Hour();
        System.out.println("Strta:::" + start);
        for (int i = 0; i < dVolume.length; i++) {
            s1.add(start, dVolume[i]);
            start = start.next();
            start = start.next();
            start = start.next();
            start = start.next();
            start = start.next();
            start = start.next();
        }
        dataset.addSeries(s1);
        return dataset;
    }

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        commoditychart chartAgent = new commoditychart();
        chartAgent.produceAllCharts("ac", "2012-04-02", "E:/images/");
        //System.exit(0);
    }
}

Я хочу, чтобы мой график отражал временные характеристики базы данных, поскольку он отражает цену и объем. Пожалуйста, помогите мне. Благодарю. Я много пробовал. Но не понял, как это сделать. Пожалуйста, если кто-нибудь знает, это поможет мне. У меня есть свои сроки.

1 Ответ

1 голос
/ 17 января 2014
OLHE O EXEMPLO ABAIXO:

/* ===========================================================
 * JFreeChart : a free chart library for the Java(tm) platform
 * ===========================================================
 *
 * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
 *
 * Project Info:  http://www.jfree.org/jfreechart/index.html
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
 * Other names may be trademarks of their respective owners.]
 *
 * -------------------------
 * TimeSeriesChartDemo1.java
 * -------------------------
 * (C) Copyright 2003-2011, by Object Refinery Limited and Contributors.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   ;
 *
 * Changes
 * -------
 * 09-Mar-2005 : Version 1, copied from the demo collection that ships with
 *               the JFreeChart Developer Guide (DG);
 *
 */

package org.jfree.chart.demo;

import java.awt.Color;
import java.text.SimpleDateFormat;

import javax.swing.JPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.RefineryUtilities;

/**
 * An example of a time series chart.  For the most part, default settings are
 * used, except that the renderer is modified to show filled shapes (as well as
 * lines) at each data point.
 */
public class TimeSeriesChartDemo1 extends ApplicationFrame {

    private static final long serialVersionUID = 1L;

    {
        // set a theme using the new shadow generator feature available in
        // 1.0.14 - for backwards compatibility it is not enabled by default
        ChartFactory.setChartTheme(new StandardChartTheme("JFree/Shadow",
                true));
    }

    /**
     * A demonstration application showing how to create a simple time series
     * chart.  This example uses monthly data.
     *
     * @param title  the frame title.
     */
    public TimeSeriesChartDemo1(String title) {
        super(title);
        ChartPanel chartPanel = (ChartPanel) createDemoPanel();
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);
    }

    /**
     * Creates a chart.
     *
     * @param dataset  a dataset.
     *
     * @return A chart.
     */
    private static JFreeChart createChart(XYDataset dataset) {

        JFreeChart chart = ChartFactory.createTimeSeriesChart(
            "Legal & General Unit Trust Prices",  // title
            "Date",             // x-axis label
            "Price Per Unit",   // y-axis label
            dataset,            // data
            true,               // create legend?
            true,               // generate tooltips?
            false               // generate URLs?
        );

        chart.setBackgroundPaint(Color.white);

        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);
        plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        plot.setDomainCrosshairVisible(true);
        plot.setRangeCrosshairVisible(true);

        XYItemRenderer r = plot.getRenderer();
        if (r instanceof XYLineAndShapeRenderer) {
            XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
            renderer.setBaseShapesVisible(true);
            renderer.setBaseShapesFilled(true);
            renderer.setDrawSeriesLineAsPath(true);
        }

        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));

        return chart;

    }

    /**
     * Creates a dataset, consisting of two series of monthly data.
     *
     * @return The dataset.
     */
    private static XYDataset createDataset() {

        TimeSeries s1 = new TimeSeries("L&G European Index Trust");
        s1.add(new Month(2, 2001), 181.8);
        s1.add(new Month(3, 2001), 167.3);
        s1.add(new Month(4, 2001), 153.8);
        s1.add(new Month(5, 2001), 167.6);
        s1.add(new Month(6, 2001), 158.8);
        s1.add(new Month(7, 2001), 148.3);
        s1.add(new Month(8, 2001), 153.9);
        s1.add(new Month(9, 2001), 142.7);
        s1.add(new Month(10, 2001), 123.2);
        s1.add(new Month(11, 2001), 131.8);
        s1.add(new Month(12, 2001), 139.6);
        s1.add(new Month(1, 2002), 142.9);
        s1.add(new Month(2, 2002), 138.7);
        s1.add(new Month(3, 2002), 137.3);
        s1.add(new Month(4, 2002), 143.9);
        s1.add(new Month(5, 2002), 139.8);
        s1.add(new Month(6, 2002), 137.0);
        s1.add(new Month(7, 2002), 132.8);

        TimeSeries s2 = new TimeSeries("L&G UK Index Trust");
        s2.add(new Month(2, 2001), 129.6);
        s2.add(new Month(3, 2001), 123.2);
        s2.add(new Month(4, 2001), 117.2);
        s2.add(new Month(5, 2001), 124.1);
        s2.add(new Month(6, 2001), 122.6);
        s2.add(new Month(7, 2001), 119.2);
        s2.add(new Month(8, 2001), 116.5);
        s2.add(new Month(9, 2001), 112.7);
        s2.add(new Month(10, 2001), 101.5);
        s2.add(new Month(11, 2001), 106.1);
        s2.add(new Month(12, 2001), 110.3);
        s2.add(new Month(1, 2002), 111.7);
        s2.add(new Month(2, 2002), 111.0);
        s2.add(new Month(3, 2002), 109.6);
        s2.add(new Month(4, 2002), 113.2);
        s2.add(new Month(5, 2002), 111.6);
        s2.add(new Month(6, 2002), 108.8);
        s2.add(new Month(7, 2002), 101.6);

        // ******************************************************************
        //  More than 150 demo applications are included with the JFreeChart
        //  Developer Guide...for more information, see:
        //
        //  >   http://www.object-refinery.com/jfreechart/guide.html
        //
        // ******************************************************************

        TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(s1);
        dataset.addSeries(s2);

        return dataset;

    }

    /**
     * Creates a panel for the demo (used by SuperDemo.java).
     *
     * @return A panel.
     */
    public static JPanel createDemoPanel() {
        JFreeChart chart = createChart(createDataset());
        ChartPanel panel = new ChartPanel(chart);
        panel.setFillZoomRectangle(true);
        panel.setMouseWheelEnabled(true);
        return panel;
    }

    /**
     * Starting point for the demonstration application.
     *
     * @param args  ignored.
     */
    public static void main(String[] args) {

        TimeSeriesChartDemo1 demo = new TimeSeriesChartDemo1(
                "Time Series Chart Demo 1");
        demo.pack();
        RefineryUtilities.centerFrameOnScreen(demo);
        demo.setVisible(true);

    }

}
...