Java和JFreechart面板

时间:2015-05-19 15:54:48

标签: java jpanel jfreechart

我已将下面的代码放在一起。 目前,一旦我运行该文件,图形就会在JFrame / Jpanel中创建,具体取决于我是否使用handleb1或handleb2。我的目标是在运行文件时,使用不包含任何值的图表创建框架,但是轴等设置并且可以看到。然后按Odiham或Wattisham,图表出现。我似乎无法解决如何做到这一点,请帮助。

package folderarray;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import static org.jfree.chart.demo.TimeSeriesChartDemo1.createDemoPanel;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Hour;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;


public class NewClass extends JFrame implements ActionListener{

Connection conexao = null;
PreparedStatement pst= null;
ResultSet rs = null;
private JButton b1,b2,b3;
private ChartPanel chartPanel;


public static void main(String[] args) throws SQLException, ParseException {
NewClass frame = new NewClass();
frame.createGUI();
frame.setSize(2500, 500);//changes size of frame
frame.setVisible(true);
}


private void createGUI() throws SQLException, ParseException {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(null);
b1 = new JButton("Odiham");
b2 = new JButton("Wattisham");

b1.setBounds(10,10,120,30);
b1.addActionListener(this);
b2.setBounds(10,80,120,30);
b2.addActionListener(this);
//b3 = new JButton("Wattisham");
//chartPanel = (ChartPanel) createDemoPanel();


//System.out.println(actionEvent.getSource());
JFreeChart chart=createChart(handleb2());



//final ChartPanel chartPanel=new ChartPanel(chart);
//JFreeChart chart = new JFreeChart("hello",parent);
ChartPanel panel = new ChartPanel(chart);
panel.setFillZoomRectangle(true);
panel.setMouseWheelEnabled(true);
panel.setBounds(900,20,1200,400);
//panel.repaint();

//JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, PlotOrientation.HORIZONTAL, true, true, true);
//chartPanel = new ChartPanel(chart);
window.add(panel);
window.add(b1);
window.add(b2);
//window.add(b3);

//b3.setBounds(10,90,120,30);
//b1.addActionListener(this);
}

@Override
public void actionPerformed (java.awt.event.ActionEvent e){
Object source = e.getSource();
if (source == b1){
    try {    
        handleb1();

    } catch (SQLException | ParseException ex) {
        Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
    }
} 

if (source == b2){
    try {    
        handleb2();
    } catch (SQLException | ParseException ex) {
        Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
    }
} 
}

private static TimeSeriesCollection handleb1() throws SQLException, ParseException{

    Connection con;
    con = null;

        con = DriverManager.getConnection("jdbc:derby://localhost:1527/Solarradiation;user=------;password=------");

        if (!con.isClosed()) {
            System.out.println("Successfully connected to the DataBase Server...");
        }


        Statement statement;
        statement = con.createStatement();

        String selectQuery = "select * from -------- where Station = 'Odiham'";
        //String selectQuery1 = "select * from ------- where Station = 'Wittering'";
        //String selectQuery2 = "select * from ---------- where Station = 'Wattisham'";
        ResultSet resultSet = null;
        //ResultSet resultSet1 = null;
        //ResultSet resultSet2 = null;
        resultSet = statement.executeQuery(selectQuery);

   //     resultSet2 = statement.executeQuery(selectQuery2);

    TimeSeries s1 = new TimeSeries("Odiham");
    while (resultSet.next()) {
    String fdata = (String) resultSet.getObject("fdate");
    String si = (String) resultSet.getObject("GLo_irra");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Date dateI = sdf2.parse(fdata);
Double production = Double.parseDouble(si);
s1.addOrUpdate(new Hour(dateI), production);
} 

resultSet.close();
/*resultSet1 = statement.executeQuery(selectQuery1);
TimeSeries s2 = new TimeSeries("Wittering");
while (resultSet1.next()) {
String fdata = (String) resultSet1.getObject("fdate");
String si = (String) resultSet1.getObject("GLo_irra");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date dateI = sdf2.parse(fdata);
Double production = Double.parseDouble(si);
s2.addOrUpdate(new Hour(dateI), production);
}

resultSet1.close();*/


/*resultSet2 = statement.executeQuery(selectQuery2);
TimeSeries s3 = new TimeSeries("Wattisham");
while (resultSet2.next()) {
String fdata = (String) resultSet2.getObject("fdate");
String si = (String) resultSet2.getObject("GLo_irra");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date dateI = sdf2.parse(fdata);
Double production = Double.parseDouble(si);
s3.addOrUpdate(new Hour(dateI), production);
}        */


 TimeSeriesCollection dataset = new TimeSeriesCollection();

 dataset.addSeries(s1); 
 //  dataset.addSeries(s2);
  // dataset.addSeries(s3);
 return dataset;
}

private static TimeSeriesCollection handleb2() throws SQLException, ParseException{

    Connection con;
    con = null;

        con = DriverManager.getConnection("jdbc:derby://localhost:1527/Solarradiation;user=-----;password=------");

        if (!con.isClosed()) {
            System.out.println("Successfully connected to the DataBase Server...");
        }
        Statement statement;
        statement = con.createStatement();

       // String selectQuery = "----------------------";
        String selectQuery = "select * from --------- where Station = 'Wattisham'";
        //String selectQuery2 = "select * from ------------ where Station = 'Wattisham'";
        ResultSet resultSet = null;
        //ResultSet resultSet1 = null;
        //ResultSet resultSet2 = null;
        resultSet = statement.executeQuery(selectQuery);
   //     resultSet2 = statement.executeQuery(selectQuery2);
    TimeSeries s1 = new TimeSeries("Wattisham");
    while (resultSet.next()) {
    String fdata = (String) resultSet.getObject("fdate");
    String si = (String) resultSet.getObject("GLo_irra");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Date dateI = sdf2.parse(fdata);
Double production = Double.parseDouble(si);
s1.addOrUpdate(new Hour(dateI), production);
} 

resultSet.close();

/*resultSet1 = statement.executeQuery(selectQuery1);
TimeSeries s2 = new TimeSeries("Wittering");
while (resultSet1.next()) {
String fdata = (String) resultSet1.getObject("fdate");
String si = (String) resultSet1.getObject("GLo_irra");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date dateI = sdf2.parse(fdata);
Double production = Double.parseDouble(si);
s2.addOrUpdate(new Hour(dateI), production);
}

resultSet1.close();*/


/*resultSet2 = statement.executeQuery(selectQuery2);
TimeSeries s3 = new TimeSeries("Wattisham");
while (resultSet2.next()) {
String fdata = (String) resultSet2.getObject("fdate");
String si = (String) resultSet2.getObject("GLo_irra");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date dateI = sdf2.parse(fdata);
Double production = Double.parseDouble(si);
s3.addOrUpdate(new Hour(dateI), production);
}        */


 TimeSeriesCollection dataset = new TimeSeriesCollection();

 dataset.addSeries(s1); 
 //  dataset.addSeries(s2);
  // dataset.addSeries(s3);

 return dataset;
}

private static JFreeChart createChart(XYDataset dataset) throws SQLException, ParseException {
JFreeChart chart = ChartFactory.createTimeSeriesChart("Solar Irradiation/Date","Date","w/m2",dataset,true,true,true);
XYPlot plot = (XYPlot) chart.getPlot();
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));
return chart;
}



}

1 个答案:

答案 0 :(得分:1)

给出一个空数据集,时间序列图表将使用轴的默认值,如下图所示。请注意,域是DateAxis,以本地时区中的Java epoch开头;范围是NumberAxis,范围为0 .. 1。默认情况下,后续更改会根据需要自动调整轴,但如果提前知道,则可以指定固定范围,如here所示。

image

在下面显示的方法中,检查问题是隔离,添加了两个任意初始值。 flag控制series随后更新还是添加

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import org.jfree.chart.*;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;

/** @See https://stackoverflow.com/a/30332903/230513 */
public class ChartPanelTest {

    private static final Random r = new Random();
    private static final TimeSeries series = new TimeSeries("Data");
    private static Day d = new Day();
    private static boolean flag = true;

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            series.add(d, 0);
            d = (Day) d.next();
            series.add(d, 0);
            XYDataset dataset = new TimeSeriesCollection(series);
            JFreeChart chart = ChartFactory.createTimeSeriesChart(
                "Test", "Day", "Value", dataset, false, false, false);
            ChartPanel chartPanel = new ChartPanel(chart) {
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(320, 240);
                }
            };
            f.add(chartPanel);
            f.add(new JButton(new AbstractAction("Add") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (flag) {
                        series.addOrUpdate(d, r.nextGaussian());
                        flag = false;
                    } else {
                        d = (Day) d.next();
                        series.add(d, r.nextGaussian());
                    }
                }
            }), BorderLayout.SOUTH);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}