Java tutorial
/* * 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 graficos; import javax.swing.JOptionPane; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYSplineRenderer; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class Grafico1 extends javax.swing.JFrame { public Grafico1() { initComponents(); this.setLocationRelativeTo(null); //se centra en el medio de la pantalla this.GraficoLinea.setVisible(false); this.GraficoBarra.setVisible(false); this.GraficoTorta.setVisible(false); this.setVisible(true); } /** * 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(); l = new javax.swing.JRadioButton(); b = new javax.swing.JRadioButton(); t = new javax.swing.JRadioButton(); Tabla = new javax.swing.JScrollPane(); datos = new javax.swing.JTable(); capas = new javax.swing.JLayeredPane(); GraficoLinea = new javax.swing.JPanel(); GraficoBarra = new javax.swing.JPanel(); GraficoTorta = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Tipo de Grafico: "); l.setText("Linea"); l.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lActionPerformed(evt); } }); b.setText("Barras"); b.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bActionPerformed(evt); } }); t.setText("Torta"); t.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tActionPerformed(evt); } }); datos.setModel(new javax.swing.table.DefaultTableModel( new Object[][] { { null, null }, { null, null }, { null, null }, { null, null }, { null, null } }, new String[] { "X", "Y" }) { Class[] types = new Class[] { java.lang.Float.class, java.lang.Float.class }; public Class getColumnClass(int columnIndex) { return types[columnIndex]; } }); Tabla.setViewportView(datos); capas.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); GraficoLinea.setBorder(new javax.swing.border.MatteBorder(null)); javax.swing.GroupLayout GraficoLineaLayout = new javax.swing.GroupLayout(GraficoLinea); GraficoLinea.setLayout(GraficoLineaLayout); GraficoLineaLayout.setHorizontalGroup(GraficoLineaLayout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 397, Short.MAX_VALUE)); GraficoLineaLayout.setVerticalGroup(GraficoLineaLayout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 423, Short.MAX_VALUE)); GraficoBarra.setBorder(new javax.swing.border.MatteBorder(null)); javax.swing.GroupLayout GraficoBarraLayout = new javax.swing.GroupLayout(GraficoBarra); GraficoBarra.setLayout(GraficoBarraLayout); GraficoBarraLayout.setHorizontalGroup(GraficoBarraLayout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 348, Short.MAX_VALUE)); GraficoBarraLayout.setVerticalGroup(GraficoBarraLayout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 423, Short.MAX_VALUE)); GraficoTorta.setBorder(new javax.swing.border.MatteBorder(null)); javax.swing.GroupLayout GraficoTortaLayout = new javax.swing.GroupLayout(GraficoTorta); GraficoTorta.setLayout(GraficoTortaLayout); GraficoTortaLayout.setHorizontalGroup(GraficoTortaLayout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 348, Short.MAX_VALUE)); GraficoTortaLayout.setVerticalGroup(GraficoTortaLayout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 423, Short.MAX_VALUE)); javax.swing.GroupLayout capasLayout = new javax.swing.GroupLayout(capas); capas.setLayout(capasLayout); capasLayout.setHorizontalGroup(capasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(capasLayout.createSequentialGroup().addContainerGap() .addComponent(GraficoLinea, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(capasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(capasLayout.createSequentialGroup().addContainerGap() .addComponent(GraficoBarra, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap())) .addGroup( capasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(capasLayout.createSequentialGroup().addContainerGap() .addComponent(GraficoTorta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()))); capasLayout.setVerticalGroup(capasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(capasLayout.createSequentialGroup().addGap(25, 25, 25) .addComponent(GraficoLinea, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(capasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(capasLayout.createSequentialGroup().addGap(15, 15, 15) .addComponent(GraficoBarra, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(23, 23, 23))) .addGroup( capasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(capasLayout.createSequentialGroup().addGap(25, 25, 25) .addComponent(GraficoTorta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()))); capas.setLayer(GraficoLinea, javax.swing.JLayeredPane.DEFAULT_LAYER); capas.setLayer(GraficoBarra, javax.swing.JLayeredPane.DEFAULT_LAYER); capas.setLayer(GraficoTorta, javax.swing.JLayeredPane.DEFAULT_LAYER); jButton1.setText("Graficar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(39, 39, 39).addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup().addComponent(l).addGap(18, 18, 18) .addComponent(b).addGap(18, 18, 18).addComponent(t)) .addComponent(jLabel1) .addComponent(Tabla, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(32, 32, 32).addComponent(capas).addContainerGap())); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(31, 31, 31).addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(capas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup().addComponent(jLabel1).addGap(34, 34, 34) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(l).addComponent(b).addComponent(t)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(Tabla, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18).addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(55, Short.MAX_VALUE))); pack(); }// </editor-fold>//GEN-END:initComponents private void lActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lActionPerformed GraficoLinea.setVisible(true); capas.setLayer(GraficoLinea, 0, 0);// Para poner el grafico arriba de las capas de graficos para que sea visible b.setSelected(false); t.setSelected(false); }//GEN-LAST:event_lActionPerformed private void tActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tActionPerformed GraficoTorta.setVisible(true); capas.setLayer(GraficoTorta, 0, 0); l.setSelected(false); b.setSelected(false); }//GEN-LAST:event_tActionPerformed private void bActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bActionPerformed GraficoBarra.setVisible(true); capas.setLayer(GraficoBarra, 0, 0); l.setSelected(false); t.setSelected(false); }//GEN-LAST:event_bActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed ChartPanel panel; JFreeChart chart = null; if (l.isSelected()) { //Grafico de Linea int ban = 1; //para validar que la tabla no esta vacia o que tenga solo caracteres numericos XYSplineRenderer renderer = new XYSplineRenderer();// renderizador XYSeriesCollection dataset = new XYSeriesCollection();// variable para almacenar los datos que le enviamos para hacer el ploteo //Ejes x , y ValueAxis x = new NumberAxis(); ValueAxis y = new NumberAxis(); XYSeries serie = new XYSeries("Datos");//almacena conjunto de datos que vamos a graficar //Le paso por parametro el nombre que recibe la serie XYPlot plot; // Hago el recorrido del JTable datos y lo agrego a la serie try { for (int fila = 0; fila < 5; fila++) { GraficoLinea.removeAll(); serie.add(Float.parseFloat(String.valueOf(datos.getValueAt(fila, 0))), Float.parseFloat(String.valueOf(datos.getValueAt(fila, 1)))); } } catch (Exception e) { ban = 0; JOptionPane.showMessageDialog(this, e.toString()); } if (ban == 1) { // Pasos claves para hacer el grafico de linea // Agrego al dataset la serie de datos. dataset.addSeries(serie); //Nombres de los ejes x.setLabel("Eje X"); y.setLabel("Eje Y"); //Ploteo pasando por parametr , el data set, los ejes y el renderer. plot = new XYPlot(dataset, x, y, renderer); chart = new JFreeChart(plot); chart.setTitle("Grafico de Lineas"); } } else { if (b.isSelected()) { //Grafico de Barra DefaultCategoryDataset data = new DefaultCategoryDataset(); // este esta hecho con datos que yo invente.. String producto1 = "Sopa Quick"; String producto2 = "Yerba Mate"; String dia1 = "Dia 1"; String dia2 = "Dia 2"; String dia3 = "Dia 3"; String dia4 = "Dia 4"; String dia5 = "Dia 5"; data.addValue(14, dia1, producto1); data.addValue(17, dia2, producto1); data.addValue(19, dia3, producto1); data.addValue(27, dia4, producto1); data.addValue(30, dia5, producto1); data.addValue(1, dia1, producto2); data.addValue(4, dia2, producto2); data.addValue(9, dia3, producto2); data.addValue(16, dia4, producto2); data.addValue(33, dia5, producto2); chart = ChartFactory.createBarChart("Grafico de Barra", "Dia", "Cantidad", data, PlotOrientation.VERTICAL, true, true, true); CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.setDomainGridlinesVisible(true); } else { //Grafico de Torta DefaultPieDataset data = new DefaultPieDataset(); data.setValue("Categoria1", 20); data.setValue("Categoria2", 400); data.setValue("Categoria3", 60); chart = ChartFactory.createPieChart3D("Grafico de Torta", data, true, true, true); } } panel = new ChartPanel(chart); panel.setBounds(5, 10, 410, 400); if (b.isSelected()) {//Barra GraficoBarra.add(panel); GraficoBarra.repaint(); } else { if (l.isSelected()) {//Linea GraficoLinea.add(panel); GraficoLinea.repaint(); } else { //Torta GraficoTorta.add(panel); GraficoTorta.repaint(); } } }//GEN-LAST:event_jButton1ActionPerformed /** * @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(Grafico1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Grafico1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Grafico1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Grafico1.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 Grafico1().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel GraficoBarra; private javax.swing.JPanel GraficoLinea; private javax.swing.JPanel GraficoTorta; private javax.swing.JScrollPane Tabla; private javax.swing.JRadioButton b; private javax.swing.JLayeredPane capas; private javax.swing.JTable datos; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JRadioButton l; private javax.swing.JRadioButton t; // End of variables declaration//GEN-END:variables }