在这里主要贴上JFreeChart做的两个小例子,分别是柱状图和动态显示JVM内存状况图。
先说明一下jfreechart的概念,jfreechart工具基本上把一个图形分成了几个逻辑部分:
      1.首先是整个的画布对象(chart),画布就相当与一个大的容器,包含一些图形元素,比如为一张白纸
      2.然后是画图区域对象(plot),就是实际图形所占据的区域,比如为白纸上的一个长方形
      3.然后是图形所需要两条轴对象(axis),比如为白纸上的两条轴线
      4.最后是如何进行图像的绘制对象(render),比如为一只画图的笔
      5.除开上面的这些对象,还有一个最主要的就是通过必须的数据集(dataset)来生成图形了
好了,其它的API就看文档了。现在开始说开发JFreeChart例子的步骤:
1. 首先下载jfreechart包。
2. 接着用MyEclipse创建一个Java Project.
3. 引用包, 要加入的包是gnujaxp.jar, jfreechart-1.0.12.jar, jcommon-1.0.15.jar
这样就把开发环境配好了,接下来就是创建类文件。先从柱状图开始.

import java.io.FileOutputStream;                                                                
                                                                                                
import org.jfree.chart.ChartFactory;                                                            
import org.jfree.chart.ChartUtilities;                                                          
import org.jfree.chart.JFreeChart;                                                              
import org.jfree.chart.plot.PlotOrientation;                                                    
import org.jfree.data.category.CategoryDataset;                                                 
import org.jfree.data.category.DefaultCategoryDataset;                                          
                                                                                                
public class BarChartDemo {                                                                     
    private static String rowKeys[] ={"Apple", "Banana", "Watermelon"};                         
    private static String columnKeys[] ={"Guangzhou", "Shanghai", "Beijing"};                   
    private static String rowKeys_zh_CN[] ={"苹果", "香蕉", "西瓜"};                            
    private static String columnKeys_zh_CN[] ={"广州", "上海", "北京"};                         
    /**                                                                                         
     * @param args                                                                              
     */                                                                                         
    public static void main(String[] args) {                                                    
        CategoryDataset dataSet = getComplexDataSet();                                          
        JFreeChart chart = ChartFactory.createBarChart("Fruit Output Chart",// 图表标题         
                "Fruit",// 目录轴的显示标签                                                     
                "Output",// 数值轴的显示标签                                                    
                dataSet,// 数据集                                                               
                PlotOrientation.VERTICAL,// 图表方向:水平、垂直                                
                true,// 是否显示图例(对于简单的柱状图必须是false)                               
                false,// 是否生成工具                                                           
                false// 是否生成URL链接                                                         
                );                                                                              
        FileOutputStream fosJPG = null;                                                         
        try {                                                                                   
            fosJPG = new FileOutputStream("D:\\fruit.jpg");                                     
            ChartUtilities.writeChartAsJPEG(fosJPG, chart, 400, 300);                           
        } catch (Exception e) {                                                                 
            e.printStackTrace();                                                                
        } finally {                                                                             
            try {                                                                               
                fosJPG.close();                                                                 
            } catch (Exception e) {                                                             
                e.printStackTrace();                                                            
            }                                                                                   
        }                                                                                       
    }                                                                                           
                                                                                                
    /**                                                                                         
     * 获取一个演示用的简单数据集对象                                                           
     *                                                                                          
     * @return                                                                                  
     */                                                                                         
    private static CategoryDataset getDataSet() {                                               
        DefaultCategoryDataset categoryDataset = new DefaultCategoryDataset();                  
        categoryDataset.addValue(100, "", rowKeys[0]);                                          
        categoryDataset.addValue(200, "", rowKeys[1]);                                          
        categoryDataset.addValue(300, "", rowKeys[2]);                                          
        return categoryDataset;                                                                 
    }                                                                                           
                                                                                                
    /**                                                                                         
     * 获取一个演示用的组合数据集对象                                                           
     *                                                                                          
     * @return                                                                                  
     */                                                                                         
    private static CategoryDataset getComplexDataSet() {                                        
        DefaultCategoryDataset categoryDataset = new DefaultCategoryDataset();                  
        categoryDataset.addValue(100, columnKeys[0], rowKeys[0]);                               
        categoryDataset.addValue(110, columnKeys[1], rowKeys[0]);                               
        categoryDataset.addValue(120, columnKeys[2], rowKeys[0]);                               
        categoryDataset.addValue(200, columnKeys[0], rowKeys[1]);                               
        categoryDataset.addValue(210, columnKeys[1], rowKeys[1]);                               
        categoryDataset.addValue(220, columnKeys[2], rowKeys[1]);                               
        categoryDataset.addValue(300, columnKeys[0], rowKeys[2]);                               
        categoryDataset.addValue(310, columnKeys[1], rowKeys[2]);                               
        categoryDataset.addValue(320, columnKeys[2], rowKeys[2]);                               
        return categoryDataset;                                                                 
    }                                                                                           
}                                                                                               
                                                                                                

 

 

运行后,可看到结果了。
接着下来是动态显示JVM内存状况图的原码.

import java.awt.BasicStroke;                                                                      
import java.awt.BorderLayout;                                                                     
import java.awt.Color;                                                                            
import java.awt.Font;                                                                             
import java.awt.event.ActionEvent;                                                                
import java.awt.event.ActionListener;                                                             
import java.awt.event.WindowAdapter;                                                              
import java.awt.event.WindowEvent;                                                                
                                                                                                  
import javax.swing.BorderFactory;                                                                 
import javax.swing.JFrame;                                                                        
import javax.swing.JPanel;                                                                        
import javax.swing.Timer;                                                                         
                                                                                                  
import org.jfree.chart.ChartPanel;                                                                
import org.jfree.chart.JFreeChart;                                                                
import org.jfree.chart.axis.DateAxis;                                                             
import org.jfree.chart.axis.NumberAxis;                                                           
import org.jfree.chart.plot.XYPlot;                                                               
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;                                        
import org.jfree.data.time.Millisecond;                                                           
import org.jfree.data.time.TimeSeries;                                                            
import org.jfree.data.time.TimeSeriesCollection;                                                  
import org.jfree.ui.RectangleInsets;                                                              
                                                                                                  
public class MemoryUsage extends JPanel {                                                         
                                                                                                  
    class DataGenerator extends Timer implements ActionListener {                                 
                                                                                                  
        /*                                                                                        
         * Invoked when an action occurs.                                                         
         *                                                                                        
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)         
         */                                                                                       
        public void actionPerformed(ActionEvent actionevent) {                                    
            long free = Runtime.getRuntime().freeMemory();                                        
            long total = Runtime.getRuntime().totalMemory();                                      
            addTotalObservation(total);                                                           
            addFreeObservation(free);                                                             
        }                                                                                         
                                                                                                  
        DataGenerator(int i) {                                                                    
            super(i, null);                                                                       
            addActionListener(this);                                                              
        }                                                                                         
    }                                                                                             
                                                                                                  
    public MemoryUsage(int maxItemAge) {                                                          
        super(new BorderLayout());                                                                
        total = new TimeSeries("Total Memory",                                                    
                org.jfree.data.time.Millisecond.class);                                           
        total.setMaximumItemAge(maxItemAge);                                                      
        free = new TimeSeries("Free Memory",                                                      
                org.jfree.data.time.Millisecond.class);                                           
        free.setMaximumItemAge(maxItemAge);                                                       
                                                                                                  
        TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();                   
        timeseriescollection.addSeries(total);                                                    
        timeseriescollection.addSeries(free);                                                     
                                                                                                  
        DateAxis dateaxis = new DateAxis("Time");                                                 
        NumberAxis numberaxis = new NumberAxis("Memory");                                         
        dateaxis.setTickLabelFont(new Font("SansSerif", 0, 12));                                  
        numberaxis.setTickLabelFont(new Font("SansSerif", 0, 12));                                
        dateaxis.setLabelFont(new Font("SansSerif", 0, 14));                                      
        numberaxis.setLabelFont(new Font("SansSerif", 0, 14));                                    
        dateaxis.setAutoRange(true);                                                              
        dateaxis.setLowerMargin(0.0D);                                                            
        dateaxis.setUpperMargin(0.0D);                                                            
        dateaxis.setTickLabelsVisible(true);                                                      
        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());                     
                                                                                                  
        XYLineAndShapeRenderer xylineandshaperenderer = new XYLineAndShapeRenderer(               
                true, false);                                                                     
        xylineandshaperenderer.setSeriesPaint(0, Color.RED); // 改变第一个Series的颜色            
        xylineandshaperenderer.setSeriesPaint(1, Color.YELLOW);// 改变第二个Series的颜色          
        xylineandshaperenderer.setSeriesStroke(0, new BasicStroke(1F, 0, 2));                     
        xylineandshaperenderer.setSeriesStroke(1, new BasicStroke(1F, 0, 2));                     
                                                                                                  
        XYPlot xyplot = new XYPlot(timeseriescollection, dateaxis, numberaxis,                    
                xylineandshaperenderer);                                                          
        xyplot.setBackgroundPaint(Color.BLACK); // 改变背景颜色                                   
        xyplot.setDomainGridlinePaint(Color.white);                                               
        xyplot.setRangeGridlinePaint(Color.white);                                                
        xyplot.setAxisOffset(new RectangleInsets(1D, 1D, 1D, 1D));                                
                                                                                                  
        JFreeChart jfreechart = new JFreeChart("JVM Memory Usage", new Font(                      
                "SansSerif", 1, 24), xyplot, true);                                               
        jfreechart.setBackgroundPaint(Color.white);                                               
                                                                                                  
        ChartPanel chartpanel = new ChartPanel(jfreechart, true);                                 
        chartpanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory                     
                .createEmptyBorder(10, 10, 10, 10), BorderFactory                                 
                .createLineBorder(Color.black)));                                                 
                                                                                                  
        add(chartpanel);                                                                          
    }                                                                                             
                                                                                                  
    private void addTotalObservation(double d) {                                                  
        total.add(new Millisecond(), d);                                                          
    }                                                                                             
                                                                                                  
    private void addFreeObservation(double d) {                                                   
        free.add(new Millisecond(), d);                                                           
    }                                                                                             
                                                                                                  
    /**                                                                                           
     * @param args                                                                                
     */                                                                                           
    public static void main(String[] args) {                                                      
        JFrame jframe = new JFrame("JVM Memory Usage");                                           
        MemoryUsage memoryusagedemo = new MemoryUsage(10000);                                     
        jframe.getContentPane().add(memoryusagedemo, "Center");                                   
        jframe.setBounds(200, 120, 1000, 500);                                                    
        jframe.setVisible(true);                                                                  
        (memoryusagedemo.new DataGenerator(1000)).start();                                        
        jframe.addWindowListener(new WindowAdapter() {                                            
            public void windowClosing(WindowEvent windowevent) {                                  
                System.exit(0);                                                                   
            }                                                                                     
        });                                                                                       
    }                                                                                             
                                                                                                  
    private TimeSeries total;                                                                     
    private TimeSeries free;                                                                      
}                                                                                                 
                                                                                                  

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐