Search code examples
javajpaneljfreechart

Java and JFreechart panel


I have put together the code below. Currently as soon as I run the file the graph is created in the JFrame/Jpanel depending if I use handleb1 or handleb2. My aim is upon running the file a frame is created with a chart that doesn't hold any values, but the axis etc is setup and can be seen. I then press Odiham or Wattisham and the graph appears. I can't seem to work out how to do this, please help.

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;
}



}

Solution

  • Give an empty dataset, a time series chart will use default values for the axes, pictured below. Note that the domain is a DateAxis starting with the Java epoch in the local time zone; the range is a NumberAxis have the range 0 .. 1. By default, subsequent changes automatically adjust the axes as needed, but you can specify a fixed range if it is known ahead of time, as shown here.

    image

    In the approach shown below, which examines the problem is isolation, two arbitrary initial values are added. A flag controls whether the series is subsequently updated or added to.

    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);
            });
        }
    }