Data.java Source code

Java tutorial

Introduction

Here is the source code for Data.java

Source

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import javax.imageio.ImageIO;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

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.XYPlot;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RectangleInsets;

@SuppressWarnings("serial")
public class Data extends JPanel {
    private static final String URL = "jdbc:mysql://192.168.188.101:3306/frigalconnectal";
    private static final String USER = "java";
    private static final String PASS = ".etml-";

    public double lastTemp;
    public double lastHum;

    parameter param = new parameter();

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */

    private static String tempUnit = "C";

    /**
     * Creates new form Data
     * @throws ClassNotFoundException 
     * @throws IOException 
     * @throws SQLException 
     */
    public Data() throws ClassNotFoundException, IOException, SQLException {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     * @throws ClassNotFoundException 
     * @throws IOException 
     * @throws SQLException 
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() throws ClassNotFoundException, IOException, SQLException {
        Connection dataFridge = getDbConnection();
        Statement stmt = dataFridge.createStatement();

        GridBagConstraints gridBagConstraints;

        panelPrincipal = new JPanel();
        panelCenter = new JPanel();
        panelHeader = new JPanel();
        btnHome = new JButton();
        dataList = new JComboBox();
        btnOk = new JButton();
        panelData = new JScrollPane();
        panelRealTime = new JPanel();
        tempRealTime = new JLabel();
        humRealTime = new JLabel();

        // Set unit temperature
        switch (param.tempUnitList.getSelectedIndex()) {
        case 0:
            tempUnit = "C";
            break;

        case 1:
            tempUnit = "F";
            break;

        default:
            break;
        }

        setPreferredSize(new Dimension(512, 400));
        setLayout(null);

        panelPrincipal.setPreferredSize(new Dimension(512, 400));
        panelPrincipal.setLayout(new BorderLayout());

        panelHeader.setPreferredSize(new Dimension(512, 40));
        panelHeader.setLayout(new GridBagLayout());

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream input = classLoader.getResourceAsStream("home.png");
        Image iconeHome = ImageIO.read(input);

        btnHome.setIcon(new ImageIcon(iconeHome));
        btnHome.setPreferredSize(new Dimension(40, 40));
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.anchor = GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new Insets(0, 0, 0, 50);
        panelHeader.add(btnHome, gridBagConstraints);

        dataList.setModel(
                new DefaultComboBoxModel(new String[] { "Donnes en temps rel", "Graphique des temperatures" }));
        dataList.setPreferredSize(new Dimension(250, 40));
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.anchor = GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new Insets(0, 0, 0, 10);
        panelHeader.add(dataList, gridBagConstraints);

        btnOk.setFont(new Font("Tahoma", 0, 10)); // NOI18N
        btnOk.setText("OK");
        btnOk.setPreferredSize(new Dimension(60, 40));
        btnOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.anchor = GridBagConstraints.LINE_START;
        gridBagConstraints.insets = new Insets(0, 5, 0, 70);
        panelHeader.add(btnOk, gridBagConstraints);

        panelPrincipal.add(panelHeader, BorderLayout.NORTH);
        panelCenter.setLayout(new BorderLayout());

        JFreeChart chart = createChart(createDataset(stmt));
        panelChart = new ChartPanel(chart);
        panelChart.setVisible(true);

        panelData = new JScrollPane(getTbleData(stmt));

        tempRealTime.setFont(new java.awt.Font("Meiryo UI", 1, 18)); // NOI18N
        humRealTime.setFont(new java.awt.Font("Meiryo UI", 1, 18)); // NOI18N

        panelRealTime.setLayout(new GridBagLayout());
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new Insets(18, 0, 0, 0);
        gridBagConstraints.anchor = GridBagConstraints.LINE_START;
        panelRealTime.add(tempRealTime, gridBagConstraints);

        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new Insets(0, 0, 10, 0);
        gridBagConstraints.anchor = GridBagConstraints.LINE_START;
        panelRealTime.add(humRealTime, gridBagConstraints);

        panelCenter.add(panelRealTime, BorderLayout.NORTH);
        panelCenter.add(panelData, BorderLayout.CENTER);

        panelPrincipal.add(panelCenter, BorderLayout.CENTER);

        add(panelPrincipal);
        panelPrincipal.setBounds(0, 0, 512, 340);

        stmt.close();
        dataFridge.close();
    }

    private JTable getTbleData(Statement stmt) throws SQLException, ClassNotFoundException {
        ResultSet rs;
        String sql = "SELECT pro_name, pro_description, COUNT(sto_uid) - (SUM(sto_inout) * 2) AS NbProduit FROM t_produit, t_stock WHERE t_produit.id_produit = t_stock.id_produit GROUP BY t_produit.id_produit";

        rs = stmt.executeQuery(sql);

        rs.last();
        Object rowData[][] = new Object[rs.getRow()][3];

        rs.beforeFirst();

        while (rs.next()) {
            rowData[rs.getRow() - 1][0] = rs.getString(1);
            rowData[rs.getRow() - 1][1] = rs.getString(2);
            rowData[rs.getRow() - 1][2] = rs.getInt(3);
        }

        sql = "SELECT tmp_temperature, tmp_humidity FROM t_temphum ORDER BY tmp_date DESC LIMIT 1";

        rs = stmt.executeQuery(sql);
        rs.first();

        if (tempUnit == "C") {
            tempRealTime.setText("Temprature : " + rs.getDouble(1) + "" + tempUnit);
        } else {
            tempRealTime.setText("Temprature : " + celsiusToFahrenheit(rs.getString(1)) + "" + tempUnit);
        }
        humRealTime.setText("Humidit : " + rs.getDouble(2) + "%");

        lastTemp = rs.getDouble(1);
        lastHum = rs.getDouble(2);

        Object columnNames[] = { "Poduit", "Description", "Quantit" };
        JTable table = new JTable(rowData, columnNames);

        return table;

    }

    private void btnOKActionPerformed(ActionEvent evt) {
        String dataChoise;
        dataChoise = (String) dataList.getSelectedItem();

        switch (dataChoise) {
        case "Donnes en temps rel":
            panelCenter.removeAll();
            panelCenter.add(panelRealTime, BorderLayout.NORTH);
            panelCenter.add(panelData, BorderLayout.CENTER);
            break;

        default:
            panelCenter.removeAll();
            panelCenter.add(panelChart);
            break;
        }
    }

    private static Connection getDbConnection() throws SQLException, ClassNotFoundException {
        //Chargement du driver
        Class.forName("com.mysql.jdbc.Driver");
        //connexion  la bd
        Connection conn = DriverManager.getConnection(URL, USER, PASS);

        return conn;
    }

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

        TimeSeries s1 = new TimeSeries("Humidit");
        TimeSeries s2 = new TimeSeries("Temprature");
        ResultSet rs = null;

        try {
            String sqlRequest = "SELECT * FROM `t_temphum`";
            rs = stmt.executeQuery(sqlRequest);
            Double hum;
            Double temp;
            Timestamp date;

            while (rs.next()) {
                hum = rs.getDouble("tmp_humidity");
                temp = rs.getDouble("tmp_temperature");
                date = rs.getTimestamp("tmp_date");

                if (tempUnit == "F") {
                    temp = celsiusToFahrenheit(temp.toString());
                }

                if (date != null) {
                    s1.add(new Second(date), hum);
                    s2.add(new Second(date), temp);
                } else {
                    JOptionPane.showMessageDialog(panelPrincipal, "Il manque une date dans la dase de donne",
                            "Date null", JOptionPane.WARNING_MESSAGE);
                }
            }

            rs.close();
        } catch (SQLException e) {
            String exception = e.toString();

            if (e.getErrorCode() == 0) {
                JOptionPane.showMessageDialog(panelPrincipal,
                        "Le serveur met trop de temps  rpondre ! Veuillez rssayer plus tard ou contacter un administrateur",
                        "Connection timed out", JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(panelPrincipal, "Voici l'exception : " + exception,
                        "Titre : exception", JOptionPane.ERROR_MESSAGE);
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (Exception e) {
            String exception = e.toString();
            JOptionPane.showMessageDialog(panelPrincipal, "Voici l'exception : " + exception, "Titre : exception",
                    JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }

        // ******************************************************************
        //  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 chart.
     *
     * @param dataset  a dataset.
     *
     * @return A chart.
     */
    private static JFreeChart createChart(XYDataset dataset) {

        JFreeChart chart = ChartFactory.createTimeSeriesChart("Graphique des tempratures et humidits", // title
                "Date", // x-axis label
                "Temperture/Humidit", // 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.white);
        plot.setDomainGridlinePaint(Color.lightGray);
        plot.setRangeGridlinePaint(Color.lightGray);
        plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        plot.setDomainCrosshairVisible(true);
        plot.setRangeCrosshairVisible(true);

        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("d.M.yy HH:mm:ss"));

        return chart;

    }

    private static double celsiusToFahrenheit(String value) {
        //TODO implement a polymorfism methode for get fahrenheit
        double degree = 0;
        int round;
        try {
            degree = Double.parseDouble(value);
        } catch (Exception e) {
            return 0;
        }

        degree = (degree * 9 / 5) + 32;

        round = (int) Math.round(degree * 100);
        // on multiplie par 100 pour arrondire  2 dcimales
        // on redivise par 100 pour avoir la vrai valeur
        return (double) round / 100;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new Data().setVisible(true);
                } catch (ClassNotFoundException | IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    // Variables declaration - do not modify
    private ChartPanel panelChart;
    private JPanel panelRealTime;
    private JLabel tempRealTime;
    private JLabel humRealTime;
    private JPanel panelCenter;
    private JScrollPane panelData;
    public JButton btnHome;
    private JButton btnOk;
    private JComboBox dataList;
    private static JPanel panelPrincipal;
    private JPanel panelHeader;
    // End of variables declaration                   

}