stockit.allStocks.java Source code

Java tutorial

Introduction

Here is the source code for stockit.allStocks.java

Source

/*
 * 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.
 */
package stockit;

import java.awt.BorderLayout;
import java.awt.Color;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 *
 * @author ahmed
 */
public class allStocks extends javax.swing.JFrame {
    private static String recievedTrader;

    /**
     * Creates new form allStocks
     */
    public allStocks() {
        initComponents();
        setupTable();
    }

    public void setupTable() {
        try {
            DBConnection dbcon = new DBConnection();
            dbcon.establishConnection();
            Statement stmt = dbcon.con.createStatement();
            ResultSet rs = stmt.executeQuery(
                    "select stock.StockID, stock.Publicly_Traded, stock.StockName, stock_sector.Sector, stock_daily_performance.Volume, stock_daily_performance.Currency, stock_daily_performance.Opening_Price, stock_daily_performance.Closing_Price, stock_daily_performance.High, stock_daily_performance.Low, stock_daily_performance.Date\n"
                            + "from stock, stock_sector, stock_daily_performance\n"
                            + "WHERE stock.StockID = stock_sector.StockID AND stock_daily_performance.StockID = stock.StockID AND stock_daily_performance.Date IN\n"
                            + "( Select * from\n" + "(\n" + "SELECT max(Date) \n"
                            + "FROM stock_daily_performance, stock\n"
                            + "where stock_daily_performance.StockID=stock.StockID\n" + "group by stock.StockID\n"
                            + "ORDER BY Date \n" + "\n" + ") temp_table)");
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.setRowCount(0);
            while (rs.next()) {
                model.addRow(new Object[] { rs.getString("StockID"), rs.getString("StockName"),
                        rs.getString("Publicly_Traded"), rs.getString("Sector"), rs.getString("Volume"),
                        rs.getString("Currency"), rs.getString("Opening_Price"), rs.getString("Closing_Price"),
                        rs.getString("High"), rs.getString("Low"), rs.getString("Date") });
            }
            dbcon.con.close();
        } catch (Exception ex) {
            Logger.getLogger(clientLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane2 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        goBackBtn = new javax.swing.JButton();
        graphPanel = new javax.swing.JPanel();
        stockPerfm = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel1.setText("Stock Market");

        table.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {

        }, new String[] { "Symbol", "Stock Name", "Public", "Sector", "Volume", "Currency", "Opening Price",
                "Closing Price", "High", "Low", "Date" }) {
            Class[] types = new Class[] { java.lang.String.class, java.lang.String.class, java.lang.String.class,
                    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class,
                    java.lang.String.class, java.lang.String.class, java.lang.String.class,
                    java.lang.String.class };
            boolean[] canEdit = new boolean[] { false, false, false, false, false, false, false, false, false,
                    false, false };

            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });
        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(table);

        goBackBtn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/stockit/rsz_undo.png"))); // NOI18N
        goBackBtn.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        goBackBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                goBackBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout graphPanelLayout = new javax.swing.GroupLayout(graphPanel);
        graphPanel.setLayout(graphPanelLayout);
        graphPanelLayout.setHorizontalGroup(graphPanelLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 0, Short.MAX_VALUE));
        graphPanelLayout.setVerticalGroup(graphPanelLayout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 0, Short.MAX_VALUE));

        stockPerfm.setText("View Stock Performance");
        stockPerfm.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        stockPerfm.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stockPerfmActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(layout.createSequentialGroup().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 829, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup().addGap(364, 364, 364).addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup().addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(goBackBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 124,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(stockPerfm, javax.swing.GroupLayout.PREFERRED_SIZE, 184,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(graphPanel, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 94,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(stockPerfm, javax.swing.GroupLayout.PREFERRED_SIZE, 34,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 297,
                                                Short.MAX_VALUE)
                                        .addComponent(goBackBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 100,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(29, 29, 29))
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(graphPanel, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addContainerGap()))));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void goBackBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goBackBtnActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_goBackBtnActionPerformed

    private void stockPerfmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stockPerfmActionPerformed
        // TODO add your handling code here:
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        int row = table.getSelectedRow();
        if (row != -1) {
            //dataset.setValue(, "", table.getValueAt(0,1).toString());
            String selectedStock = table.getValueAt(row, 0).toString();
            try {
                DBConnection dbcon = new DBConnection();
                dbcon.establishConnection();
                Statement stmt = dbcon.con.createStatement();
                ResultSet rs = stmt
                        .executeQuery("Select stock_daily_performance.Closing_Price, stock_daily_performance.Date\n"
                                + "FROM stock_daily_performance, stock\n"
                                + "WHERE stock_daily_performance.StockID = stock.StockID AND stock.StockID = '"
                                + selectedStock + "'" + "AND Date IN\n" + "( Select * from\n" + "(\n"
                                + "SELECT Date \n" + "FROM stock_daily_performance \n"
                                + "WHERE StockID = stockID \n" + "ORDER BY Date ASC\n" + ") temp_table)\n"
                                + "            ");

                while (rs.next()) {

                    String formattedDate = rs.getString("Date");
                    int closing_price = rs.getInt("Closing_Price");
                    System.out.println("Closing Price: " + closing_price);
                    System.out.println("Date: " + formattedDate);
                    dataset.setValue(closing_price, "value", formattedDate);

                }
                dbcon.con.close();
            } catch (Exception ex) {
                Logger.getLogger(clientLogin.class.getName()).log(Level.SEVERE, null, ex);
            }
            String stockName = table.getValueAt(row, 1).toString();
            JFreeChart chart = ChartFactory.createLineChart(stockName + " Stock Performance", "Date", "Value",
                    dataset, PlotOrientation.VERTICAL, false, false, false);
            Color c = new Color(240, 240, 240, 0);
            chart.setBackgroundPaint(c);
            CategoryPlot catPlot = chart.getCategoryPlot();
            catPlot.setRangeGridlinePaint(Color.BLACK);
            //set interval of Y-axis ticks (tick every 5 units)
            NumberAxis yAxis = (NumberAxis) catPlot.getRangeAxis();
            yAxis.setTickUnit(new NumberTickUnit(5));

            //set y-axis labels as currency types ($)
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            yAxis.setNumberFormatOverride(currency);

            //setting number of lines an x-axis label is displayed on
            CategoryAxis categoryAxis = catPlot.getDomainAxis();
            categoryAxis.setMaximumCategoryLabelLines(4);
            graphPanel.setLayout(new java.awt.BorderLayout());
            ChartPanel chartPanel = new ChartPanel(chart);
            graphPanel.removeAll();
            graphPanel.add(chartPanel, BorderLayout.CENTER);
            graphPanel.validate();
            graphPanel.repaint();
        }
    }//GEN-LAST:event_stockPerfmActionPerformed

    /**
     * @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 (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(allStocks.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(allStocks.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(allStocks.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(allStocks.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        }
        //</editor-fold>
        recievedTrader = args[0];
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new allStocks().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton goBackBtn;
    private javax.swing.JPanel graphPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton stockPerfm;
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables
}