Java tutorial
import java.util.*; import java.io.*; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Checkbox; import java.awt.Color; import java.io.File; import java.io.IOException; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; import org.jfree.chart.axis.*; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.statistics.Regression; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; /* * 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. */ /** * * @author JCisneros77 */ public class GraficasForm extends javax.swing.JFrame { public Vector<Record> fileCandidatos = new Vector<Record>(); public Vector<Record> filePartidos = new Vector<Record>(); Vector<JCheckBox> candidatosCB = new Vector<JCheckBox>(); Vector<JCheckBox> partidosCB = new Vector<JCheckBox>(); String[] candidatosKeys = { "LincolnChaffee", "HillaryClinton", "MartinOMalley", "BernieSanders", "JimWebb", "RandPaul", "JebBush", "BenCarson", "ChrisChristie", "TedCruz", "FiorinaCarly", "LindseyGraham", "BobbyJindal", "JohnKasich", "Pataki", "MarcoRubio", "RickSantorum", "DonaldTrump" }; String[] partidosKeys = { "Democrat", "Republican" }; /** * Creates new form GraficasForm */ public GraficasForm() { XYLineChartExample chart; initComponents(); Record r = new Record(); fileCandidatos = r.readFile("Candidates.txt"); filePartidos = r.readFile("Parties.txt"); ButtonGroup group = new ButtonGroup(); group.add(candidatosRadio); group.add(partidosRadio); candidatosCB.add(lincolnChaffeeCB); candidatosCB.add(hillaryClintonCB); candidatosCB.add(martinOMalleyCB); candidatosCB.add(bernieSandersCB); candidatosCB.add(jimWebbCB); candidatosCB.add(randPaulCB); candidatosCB.add(jebBushCB); candidatosCB.add(benCarsonCB); candidatosCB.add(chrisChristieCB); candidatosCB.add(tedCruzCB); candidatosCB.add(carlyFiorinaCB); candidatosCB.add(lindseyGrahamCB); candidatosCB.add(bobbyJindalCB); candidatosCB.add(johnKasichCB); candidatosCB.add(georgePatakiCB); candidatosCB.add(marcoRubioCB); candidatosCB.add(rickSantorumCB); candidatosCB.add(donaldTrumpCB); partidosCB.add(democrataCB); partidosCB.add(republicanoCB); partidosRadio.setSelected(true); partidosCB.elementAt(0).setSelected(true); partidosCB.elementAt(1).setSelected(true); for (int i = 0; i < candidatosCB.size(); ++i) { candidatosCB.elementAt(i).setEnabled(false); candidatosCB.elementAt(i).setSelected(false); } Vector<String> keys = new Vector<String>(); keys.add("Democrat"); keys.add("Republican"); chart = new XYLineChartExample(); panelGrafica.add(chart.createChartPanel(keys), BorderLayout.CENTER); panelGrafica.revalidate(); panelGrafica.repaint(); //panelGrafica = chart.createChartPanel(); //add(panelGrafica); } /** * 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() { panelGrafica = new javax.swing.JPanel(); graficarButton = new javax.swing.JButton(); lincolnChaffeeCB = new javax.swing.JCheckBox(); hillaryClintonCB = new javax.swing.JCheckBox(); martinOMalleyCB = new javax.swing.JCheckBox(); bernieSandersCB = new javax.swing.JCheckBox(); jimWebbCB = new javax.swing.JCheckBox(); benCarsonCB = new javax.swing.JCheckBox(); randPaulCB = new javax.swing.JCheckBox(); jebBushCB = new javax.swing.JCheckBox(); marcoRubioCB = new javax.swing.JCheckBox(); georgePatakiCB = new javax.swing.JCheckBox(); johnKasichCB = new javax.swing.JCheckBox(); bobbyJindalCB = new javax.swing.JCheckBox(); lindseyGrahamCB = new javax.swing.JCheckBox(); carlyFiorinaCB = new javax.swing.JCheckBox(); tedCruzCB = new javax.swing.JCheckBox(); chrisChristieCB = new javax.swing.JCheckBox(); donaldTrumpCB = new javax.swing.JCheckBox(); rickSantorumCB = new javax.swing.JCheckBox(); candidatosRadio = new javax.swing.JRadioButton(); partidosRadio = new javax.swing.JRadioButton(); democrataCB = new javax.swing.JCheckBox(); republicanoCB = new javax.swing.JCheckBox(); jLabel1 = new javax.swing.JLabel(); totalTweets = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); panelGrafica.setLayout(new java.awt.BorderLayout()); graficarButton.setText("Graficar"); graficarButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { graficarButtonActionPerformed(evt); } }); lincolnChaffeeCB.setText("Lincoln Chaffee"); hillaryClintonCB.setText("Hillary Clinton"); martinOMalleyCB.setText("Martin O Malley"); bernieSandersCB.setText("Bernie Sanders"); jimWebbCB.setText("Jim Webb"); benCarsonCB.setText("Ben Carson"); randPaulCB.setText("Rand Paul"); jebBushCB.setText("Jeb Bush"); marcoRubioCB.setText("Marco Rubio"); georgePatakiCB.setText("George Pataki"); johnKasichCB.setText("John Kasich"); bobbyJindalCB.setText("Bobby Jindal"); lindseyGrahamCB.setText("Lindsey Graham"); carlyFiorinaCB.setText("Carly Fiorina"); tedCruzCB.setText("Ted Cruz"); chrisChristieCB.setText("Chris Christie"); donaldTrumpCB.setText("Donald Trump"); rickSantorumCB.setText("Rick Santorum"); candidatosRadio.setText("Por Candidatos"); candidatosRadio.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { candidatosRadioActionPerformed(evt); } }); partidosRadio.setText("Por Partido"); partidosRadio.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { partidosRadioActionPerformed(evt); } }); democrataCB.setText("Democrata"); republicanoCB.setText("Republicano"); jLabel1.setText("Total de Tweets Analizados:"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup().addGap(17, 17, 17) .addComponent(panelGrafica, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 693, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(9, 9, 9).addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lincolnChaffeeCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(hillaryClintonCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(martinOMalleyCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bernieSandersCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jimWebbCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(randPaulCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jebBushCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(benCarsonCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chrisChristieCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tedCruzCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(carlyFiorinaCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lindseyGrahamCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bobbyJindalCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(johnKasichCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(georgePatakiCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(marcoRubioCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(rickSantorumCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(donaldTrumpCB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(candidatosRadio)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(partidosRadio) .addGroup(layout.createSequentialGroup().addGap(12, 12, 12).addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(democrataCB).addComponent(republicanoCB))))) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(graficarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(50, 50, 50)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE).addComponent(jLabel1) .addGap(18, 18, 18).addComponent(totalTweets).addGap(141, 141, 141))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup( layout.createSequentialGroup().addGap(7, 7, 7) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1).addComponent(totalTweets)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelGrafica, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup().addComponent(partidosRadio) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(democrataCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(republicanoCB)) .addGroup(layout.createSequentialGroup().addComponent(candidatosRadio) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lincolnChaffeeCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(hillaryClintonCB))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(martinOMalleyCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bernieSandersCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jimWebbCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(randPaulCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jebBushCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(benCarsonCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chrisChristieCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tedCruzCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(carlyFiorinaCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lindseyGrahamCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bobbyJindalCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(johnKasichCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(georgePatakiCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(marcoRubioCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rickSantorumCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(donaldTrumpCB))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(graficarButton).addContainerGap(9, Short.MAX_VALUE))); pack(); }// </editor-fold>//GEN-END:initComponents private void graficarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_graficarButtonActionPerformed Vector<String> keys = new Vector<String>(); Vector<Integer> indexes = new Vector<Integer>(); Boolean candSelected = false; if (candidatosRadio.isSelected()) { candSelected = true; indexes = getCandidatosSelected(); } else { indexes = getPartidosSelected(); } if (indexes.isEmpty()) { JOptionPane.showMessageDialog(null, "Escoja al menos un dato para graficar."); return; } else { if (candSelected) { for (int j = 0; j < indexes.size(); ++j) { keys.add(candidatosKeys[indexes.elementAt(j)]); } } else { for (int j = 0; j < indexes.size(); ++j) { keys.add(partidosKeys[indexes.elementAt(j)]); } } } panelGrafica.removeAll(); XYLineChartExample chart = new XYLineChartExample(); panelGrafica.add(chart.createChartPanel(keys), BorderLayout.CENTER); panelGrafica.revalidate(); panelGrafica.repaint(); }//GEN-LAST:event_graficarButtonActionPerformed private Vector getCandidatosSelected() { Vector<Integer> candidatos = new Vector<Integer>(); for (int i = 0; i < candidatosCB.size(); ++i) { if (candidatosCB.elementAt(i).isSelected()) candidatos.add(i); } return candidatos; } private Vector getPartidosSelected() { Vector<Integer> partidos = new Vector<Integer>(); for (int i = 0; i < partidosCB.size(); ++i) { if (partidosCB.elementAt(i).isSelected()) partidos.add(i); } return partidos; } private void candidatosRadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_candidatosRadioActionPerformed if (candidatosRadio.isSelected()) { for (int i = 0; i < partidosCB.size(); ++i) { partidosCB.elementAt(i).setEnabled(false); partidosCB.elementAt(i).setSelected(false); } for (int i = 0; i < candidatosCB.size(); ++i) { candidatosCB.elementAt(i).setEnabled(true); candidatosCB.elementAt(i).setSelected(false); } } }//GEN-LAST:event_candidatosRadioActionPerformed private void partidosRadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_partidosRadioActionPerformed if (partidosRadio.isSelected()) { for (int i = 0; i < partidosCB.size(); ++i) { partidosCB.elementAt(i).setEnabled(true); partidosCB.elementAt(i).setSelected(false); } for (int i = 0; i < candidatosCB.size(); ++i) { candidatosCB.elementAt(i).setEnabled(false); candidatosCB.elementAt(i).setSelected(false); } } }//GEN-LAST:event_partidosRadioActionPerformed /** * @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(GraficasForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GraficasForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GraficasForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GraficasForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new GraficasForm().setVisible(true); } }); } public class XYLineChartExample extends javax.swing.JPanel { Vector<String> dates = new Vector<String>(); Vector<XYSeries> series = new Vector<XYSeries>(); public XYLineChartExample() { //super("XY Line Chart Example with JFreechart"); //Record r = new Record(); //fileCandidatos = r.readFile("Candidates.txt"); //filePartidos = r.readFile("Parties.txt"); //JPanel graficaPanel = createChartPanel(keys); //add(graficaPanel); //setSize(640, 480); //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setLocationRelativeTo(null); } private JPanel createChartPanel(Vector<String> keys) { String chartTitle = "US Elections 2016"; String xAxisLabel = "X"; String yAxisLabel = "Y"; Vector<Record> fileAUsar = new Vector<Record>(); Record r = new Record(); if (candidatosRadio.isSelected()) fileAUsar = fileCandidatos; else fileAUsar = filePartidos; Vector<Record> vectorRecords = new Vector<Record>(); //Acomodar vector por fecha for (int i = 0; i < keys.size(); ++i) { for (int j = 0; j < fileAUsar.size(); ++j) { if (keys.elementAt(i).equals(fileAUsar.elementAt(j).getName())) { vectorRecords.add(fileAUsar.elementAt(j)); } } } r.v = vectorRecords; r.orderByDate(vectorRecords, 0, vectorRecords.size() - 1); vectorRecords = r.v; XYDataset dataset = createDataset(vectorRecords); JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, xAxisLabel, yAxisLabel, dataset); // boolean showLegend = false; // boolean createURL = false; // boolean createTooltip = false; // // JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, // xAxisLabel, yAxisLabel, dataset, // PlotOrientation.HORIZONTAL, showLegend, createTooltip, createURL); //Vector<String> fechas = new Vector<String>(); String[] datesArray = new String[dates.size()]; dates.toArray(datesArray); XYPlot plot = (XYPlot) chart.getPlot(); plot.setForegroundAlpha(0.5f); SymbolAxis domainAxis = new SymbolAxis("Dates", datesArray); domainAxis.setTickUnit(new NumberTickUnit(1)); domainAxis.setRange(0, datesArray.length); plot.setDomainAxis(domainAxis); customizeChart(chart); // saves the chart as an image files File imageFile = new File("XYLineChart.png"); int width = 640; int height = 480; try { ChartUtilities.saveChartAsPNG(imageFile, chart, width, height); } catch (IOException ex) { System.err.println(ex); } if (keys.size() == 1) chart = drawRegressionLine(dataset, chart); return new ChartPanel(chart); } private int searchDate(String date) { int i = 0; Boolean found = false; for (i = 0; i < dates.size(); ++i) { if (date.equals(dates.elementAt(i))) { found = true; break; } } if (found) return i; else { dates.add(date); return (dates.size() - 1); } } private int searchKey(String key) { int i = 0; Boolean found = false; for (i = 0; i < series.size(); ++i) { if (key.equals(series.elementAt(i).getKey())) { found = true; break; } } if (found) return i; else { XYSeries temp = new XYSeries(key); series.add(temp); return (series.size() - 1); } } private XYDataset createDataset(Vector<Record> keys) { String[] fechas = { "2015-11-18", "2015-11-19", "2015-11-20", "2015-11-21", "2015-11-22", "2015-11-23", "2015-11-24" }; XYSeriesCollection dataset = new XYSeriesCollection(); for (int i = 0; i < keys.size(); ++i) { int index = searchKey(keys.elementAt(i).getName()); XYSeries temp = series.elementAt(index); temp.add(searchDate(keys.elementAt(i).getDate()), keys.elementAt(i).getAmount()); } for (int i = 0; i < fechas.length; ++i) { searchDate(fechas[i]); } for (int j = 0; j < series.size(); ++j) { XYSeries temp = series.elementAt(j); dataset.addSeries(temp); } return dataset; } private JFreeChart drawRegressionLine(XYDataset inputData, JFreeChart chart) { // Get the parameters 'a' and 'b' for an equation y = a + b * x, // fitted to the inputData using ordinary least squares regression. // a - regressionParameters[0], b - regressionParameters[1] double regressionParameters[] = Regression.getOLSRegression(inputData, 0); // Prepare a line function using the found parameters LineFunction2D linefunction2d = new LineFunction2D(regressionParameters[0], regressionParameters[1]); // Creates a dataset by taking sample values from the line function XYDataset dataset = DatasetUtilities.sampleFunction2D(linefunction2d, 0D, 300, 100, "Prediccin de popularidad."); // Draw the line dataset XYPlot xyplot = chart.getXYPlot(); xyplot.setDataset(1, dataset); XYLineAndShapeRenderer xylineandshaperenderer = new XYLineAndShapeRenderer(true, false); xylineandshaperenderer.setSeriesPaint(0, Color.YELLOW); xyplot.setRenderer(1, xylineandshaperenderer); return chart; } private void customizeChart(JFreeChart chart) { XYPlot plot = chart.getXYPlot(); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); // sets paint color for each series renderer.setSeriesPaint(0, Color.RED); renderer.setSeriesPaint(1, Color.GREEN); renderer.setSeriesPaint(2, Color.YELLOW); // sets thickness for series (using strokes) renderer.setSeriesStroke(0, new BasicStroke(4.0f)); renderer.setSeriesStroke(1, new BasicStroke(3.0f)); renderer.setSeriesStroke(2, new BasicStroke(2.0f)); // sets paint color for plot outlines plot.setOutlinePaint(Color.BLUE); plot.setOutlineStroke(new BasicStroke(2.0f)); // sets renderer for lines plot.setRenderer(renderer); // sets plot background plot.setBackgroundPaint(Color.DARK_GRAY); // sets paint color for the grid lines plot.setRangeGridlinesVisible(true); plot.setRangeGridlinePaint(Color.BLACK); plot.setDomainGridlinesVisible(true); plot.setDomainGridlinePaint(Color.BLACK); } /*public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new XYLineChartExample().setVisible(true); } }); }*/ } class Record { String name; String date; int amount; public Vector<Record> v = new Vector<Record>(); public Record() { } public Record(String name, String date, int amount) { this.name = name; this.date = date; this.amount = amount; } public String getName() { return this.name; } public String getDate() { return this.date; } public int getAmount() { return this.amount; } public Vector readFile(String filename) { Vector<String> lines = new Vector<String>(); int cont = 0; try { FileInputStream fstream = new FileInputStream(filename); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { lines.add(strLine); } in.close(); } catch (IOException e) { System.out.println("Couldn't Open File Error: " + e); } for (int k = 0; k < lines.size(); ++k) { String strLine = lines.elementAt(k); String nextLine = "NULL"; if (k + 1 < lines.size()) nextLine = lines.elementAt(k + 1); int positives, negatives; String[] tokens = strLine.split("#"); String posOrNeg; String amount = ""; posOrNeg = tokens[2].substring(0, 1); for (int i = 1; i < tokens[2].length(); ++i) { char c = tokens[2].charAt(i); if (c >= '0' && c <= '9') { amount = tokens[2].substring(i); break; } } String[] tokensNextLine = nextLine.split("#"); String posOrNegNextLine; String amountNextLine = ""; //Si son el mismo registro if (tokens[0].equals(tokensNextLine[0]) && tokens[1].equals(tokensNextLine[1])) { posOrNegNextLine = tokensNextLine[2].substring(0, 1); for (int i = 1; i < tokensNextLine[2].length(); ++i) { char c = tokensNextLine[2].charAt(i); if (c >= '0' && c <= '9') { amountNextLine = tokensNextLine[2].substring(i); k++; break; } } if (posOrNeg.equals("0")) { //0 Negative, 1 Positive negatives = Integer.parseInt(amount) * -1; positives = Integer.parseInt(amountNextLine); } else { negatives = Integer.parseInt(amountNextLine) * -1; positives = Integer.parseInt(amount); } } else { // No tiene registro (0 en alguno) if (posOrNeg.equals("0")) { negatives = Integer.parseInt(amount) * -1; positives = 0; } else { negatives = 0; positives = Integer.parseInt(amount); } } cont += positives + (-1 * negatives); Record record = new Record(tokens[0], tokens[1], positives + negatives); v.add(record); } if (filename.equals("Candidates.txt")) totalTweets.setText(cont + ""); orderByDate(v, 0, v.size() - 1); return v; } public void orderByDate(Vector<Record> v, int left, int right) { int index = partition(v, left, right); if (left < index - 1) orderByDate(v, left, index - 1); if (index < right) orderByDate(v, index, right); } public int getDateRelation(String date1, String date2) { //0 => Igual 1 => Menor 2 => Mayor String[] elements1 = date1.split("-"); String[] elements2 = date2.split("-"); int day1 = Integer.parseInt(elements1[2]); int month1 = Integer.parseInt(elements1[1]); int year1 = Integer.parseInt(elements1[0]); int day2 = Integer.parseInt(elements2[2]); int month2 = Integer.parseInt(elements2[1]); int year2 = Integer.parseInt(elements2[0]); if (year1 == year2 && month1 == month2 && day1 == day2) return 0; else { if (year1 == year2) { if (month1 == month2) { if (day1 < day2) return 1; else return 2; } else if (month1 < month2) return 1; else return 2; } else if (year1 < year2) return 1; else return 2; } } public int partition(Vector<Record> arr, int left, int right) { int i = left, j = right; Record pivot = arr.elementAt((left + right) / 2); while (i <= j) { while (getDateRelation(arr.elementAt(i).getDate(), pivot.getDate()) == 1) i++; while (getDateRelation(arr.elementAt(j).getDate(), pivot.getDate()) == 2) j--; if (i <= j) { Record tmp = arr.elementAt(i); arr.set(i, arr.elementAt(j)); arr.set(j, tmp); i++; j--; } } return i; } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox benCarsonCB; private javax.swing.JCheckBox bernieSandersCB; private javax.swing.JCheckBox bobbyJindalCB; private javax.swing.JRadioButton candidatosRadio; private javax.swing.JCheckBox carlyFiorinaCB; private javax.swing.JCheckBox chrisChristieCB; private javax.swing.JCheckBox democrataCB; private javax.swing.JCheckBox donaldTrumpCB; private javax.swing.JCheckBox georgePatakiCB; private javax.swing.JButton graficarButton; private javax.swing.JCheckBox hillaryClintonCB; private javax.swing.JLabel jLabel1; private javax.swing.JCheckBox jebBushCB; private javax.swing.JCheckBox jimWebbCB; private javax.swing.JCheckBox johnKasichCB; private javax.swing.JCheckBox lincolnChaffeeCB; private javax.swing.JCheckBox lindseyGrahamCB; private javax.swing.JCheckBox marcoRubioCB; private javax.swing.JCheckBox martinOMalleyCB; private javax.swing.JPanel panelGrafica; private javax.swing.JRadioButton partidosRadio; private javax.swing.JCheckBox randPaulCB; private javax.swing.JCheckBox republicanoCB; private javax.swing.JCheckBox rickSantorumCB; private javax.swing.JCheckBox tedCruzCB; private javax.swing.JLabel totalTweets; // End of variables declaration//GEN-END:variables }