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                   
}

 

posted @ 2020-08-27 16:54  龙欺  阅读(550)  评论(0)    收藏  举报