1. 程式人生 > 實用技巧 >java圖形(柱形圖,折線圖,餅狀圖)

java圖形(柱形圖,折線圖,餅狀圖)

/*
 * 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 t2;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat; import java.util.Vector; import javax.swing.JFrame; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xslf.usermodel.BarChartDemo; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jfree.chart.ChartPanel; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartFrame; import org.jfree.chart.JFreeChart; import org.jfree.chart.StandardChartTheme; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.CategoryLabelPositions; import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.labels.ItemLabelAnchor; import org.jfree.chart.labels.ItemLabelPosition; import org.jfree.chart.labels.StandardXYItemLabelGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.LineAndShapeRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.title.TextTitle; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.time.TimeSeries; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.ui.TextAnchor; /** * * @author Lenovo */ public class t2 extends javax.swing.JFrame { /** * Creates new form t2 */ public t2() { 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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); table = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); pane = new java.awt.Panel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("宋體", 1, 24)); // NOI18N jLabel1.setText("資料展示器"); table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "名稱", "資料" } )); jScrollPane1.setViewportView(table); jButton1.setText("曲線資料"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("餅狀資料"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("柱狀資料"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout paneLayout = new javax.swing.GroupLayout(pane); pane.setLayout(paneLayout); paneLayout.setHorizontalGroup( paneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 385, Short.MAX_VALUE) ); paneLayout.setVerticalGroup( paneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pane, 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() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(1, 1, 1) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(pane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()))) ); pack(); }// </editor-fold> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: Vector vector=new Vector(); Vector vector2=new Vector(); try{ File file = new File("D:\\曲線圖資料.xlsx"); FileInputStream fis = new FileInputStream(file); Workbook wb=new XSSFWorkbook(file); Sheet filesheet=(Sheet)wb.getSheet("Sheet1"); int numrows =filesheet.getLastRowNum()-filesheet.getFirstRowNum(); for(int i=0;i<=numrows;i++){ Row row=filesheet.getRow(i); //獲取每列的資料 String title1=row.getCell(0).getStringCellValue(); vector.add(title1); int title2=(int)row.getCell(1).getNumericCellValue(); vector2.add(title2); // table.getModel().setValueAt(title1,i,0); table.getModel().setValueAt(title2,i,1); } DefaultCategoryDataset mDataset = new DefaultCategoryDataset(); for(int i=0;i<vector.size()||i<vector2.size();i++){ mDataset.addValue((int)vector2.get(i),String.valueOf(vector.get(i)), String.valueOf(vector.get(i))); StandardChartTheme mChartTheme = new StandardChartTheme("CN"); mChartTheme.setLargeFont(new Font("黑體", Font.BOLD, 20)); mChartTheme.setExtraLargeFont(new Font("宋體", Font.PLAIN, 15)); mChartTheme.setRegularFont(new Font("宋體", Font.PLAIN, 15)); ChartFactory.setChartTheme(mChartTheme); JFreeChart chart = ChartFactory.createLineChart( "曲線圖",//圖名字 "名稱",//橫座標 "數量",//縱座標 mDataset,//資料集 PlotOrientation.VERTICAL, true, // 顯示圖例 true, // 採用標準生成器 false);// 是否生成超連結 chart.setTextAntiAlias(false); chart.setBackgroundPaint(Color.WHITE); // 設定圖示題的字型重新設定title Font font = new Font("隸書", Font.BOLD, 25); TextTitle title = new TextTitle("曲線圖"); title.setFont(font); chart.setTitle(title); // 設定面板字型 Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12); chart.setBackgroundPaint(Color.WHITE); CategoryPlot categoryplot = (CategoryPlot) chart.getPlot(); // x軸 // 分類軸網格是否可見 categoryplot.setDomainGridlinesVisible(true); // y軸 //資料軸網格是否可見 categoryplot.setRangeGridlinesVisible(true); categoryplot.setRangeGridlinePaint(Color.WHITE);// 虛線色彩 categoryplot.setDomainGridlinePaint(Color.WHITE);// 虛線色彩 categoryplot.setBackgroundPaint(Color.lightGray); // 設定軸和麵板之間的距離 // categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D)); CategoryAxis domainAxis = categoryplot.getDomainAxis(); domainAxis.setLabelFont(labelFont);// 軸標題 domainAxis.setTickLabelFont(labelFont);// 軸數值 domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 橫軸上的 // Lable // 45度傾斜 // 設定距離圖片左端距離 domainAxis.setLowerMargin(0.0); // 設定距離圖片右端距離 domainAxis.setUpperMargin(0.0); NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis(); numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); numberaxis.setAutoRangeIncludesZero(true); LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot .getRenderer(); lineandshaperenderer.setBaseShapesVisible(true); // series 點(即資料點)可見 lineandshaperenderer.setBaseLinesVisible(true); // series 點(即資料點)間有連線可見 ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setSize(pane.getSize()); pane.removeAll(); pane.add(chartPanel); pane.validate(); } }catch(Exception ex) { javax.swing.JOptionPane.showMessageDialog(rootPane,ex.toString()); }finally{ vector.clear(); vector2.clear(); } } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: Vector vector=new Vector(); Vector vector2=new Vector(); try{ File file = new File("D:\\餅狀圖資料.xlsx"); FileInputStream fis = new FileInputStream(file); Workbook wb=new XSSFWorkbook(file); Sheet filesheet=(Sheet)wb.getSheet("Sheet1"); int numrows =filesheet.getLastRowNum()-filesheet.getFirstRowNum(); for(int i=0;i<=numrows;i++){ Row row=filesheet.getRow(i); //獲取每列的資料 String title1=row.getCell(0).getStringCellValue(); vector.add(title1); int title2=(int)row.getCell(1).getNumericCellValue(); vector2.add(title2); // table.getModel().setValueAt(title1,i,0); table.getModel().setValueAt(title2,i,1); } DefaultPieDataset dataset = new DefaultPieDataset(); for(int i=0;i<vector.size()||i<vector2.size();i++){ dataset.setValue(String.valueOf(vector.get(i)),(int)vector2.get(i)); JFreeChart chart = ChartFactory.createPieChart("餅狀圖", dataset, true, true,false); chart.getLegend().setItemFont(new Font("宋體",Font.BOLD,15)); chart.getTitle().setFont(new Font("宋體",Font.BOLD,18)); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setSize(pane.getSize()); pane.removeAll(); pane.add(chartPanel); pane.validate(); } }catch(Exception ex) { javax.swing.JOptionPane.showMessageDialog(rootPane,ex.toString()); }finally{ vector.clear(); vector2.clear(); } } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: Vector vector=new Vector(); Vector vector2=new Vector(); try{ File file = new File("D:\\柱狀圖資料.xlsx"); FileInputStream fis = new FileInputStream(file); Workbook wb=new XSSFWorkbook(file); Sheet filesheet=(Sheet)wb.getSheet("Sheet1"); int numrows =filesheet.getLastRowNum()-filesheet.getFirstRowNum(); for(int i=0;i<=numrows;i++){ Row row=filesheet.getRow(i); //獲取每列的資料 String title1=row.getCell(0).getStringCellValue(); vector.add(title1); int title2=(int)row.getCell(1).getNumericCellValue(); vector2.add(title2); // table.getModel().setValueAt(title1,i,0); table.getModel().setValueAt(title2,i,1); } DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for(int i=0;i<vector.size()||i<vector2.size();i++){ dataset.setValue((int)vector2.get(i),String.valueOf(vector.get(i)),String.valueOf(vector.get(i))); JFreeChart chart = ChartFactory.createBarChart("柱狀圖","名稱","數量",dataset,PlotOrientation.VERTICAL, true, true,false); CategoryPlot plot = (CategoryPlot) chart.getCategoryPlot(); CategoryAxis axis = plot.getDomainAxis(); axis.setLabelFont(new Font("宋體", Font.BOLD, 20)); axis.setTickLabelFont(new Font("宋體", Font.BOLD, 20)); ValueAxis rangeAxis = plot.getRangeAxis(); rangeAxis.setLabelFont(new Font("宋體", Font.BOLD, 20)); chart.getLegend().setItemFont(new Font("宋體", Font.BOLD, 20)); chart.getTitle().setFont(new Font("黑體", Font.ITALIC, 22)); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setSize(pane.getSize()); pane.removeAll(); pane.add(chartPanel); pane.validate(); } }catch(Exception ex) { javax.swing.JOptionPane.showMessageDialog(rootPane,ex.toString()); }finally{ vector.clear(); vector2.clear(); } } /** * @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(t2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(t2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(t2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(t2.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 t2().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private java.awt.Panel pane; private javax.swing.JTable table; // End of variables declaration }