码迷,mamicode.com
首页 > 其他好文 > 详细

swt动态图表实例

时间:2015-06-30 18:33:20      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:swt动态图表   jfreechart   

前段时间做了个linux信息采集系统,目的是在windows环境下监测linx主机的资源使用情况以及硬件的健康状况,采集到信息后需要以动态图表的形式显示出来,由于使用的swt的来做的界面,上网收缩后发现相关的资料很少,要么不能用,要么不适合,于是决定写个demo,方便以后使用,希望对有需要的人有所帮助。本demo使用的是jfreechart组件,这个demo是根据官网的demo改的,为了方便使用LinkedHashMap来维护数据,因为这是有序的,而且可以通过重写removeEldestEntry()方法来对数据进行刷新。由于是个demo,所以数据是随机生成的。接下来就上代码吧:
相关jar包下载地址:http://download.csdn.net/detail/q5841818/8854819
将下面这两个类放在同一包下,编译即可运行

import java.util.LinkedHashMap;
import java.util.Map;

import org.jfree.data.time.Second;

public class MyMap extends LinkedHashMap<Second, Integer>{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private static final int MAX_ENTRIES = 9;

    protected boolean removeEldestEntry(Map.Entry eldest) {
       return size() > MAX_ENTRIES;
    }
import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.Map.Entry;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.experimental.chart.swt.ChartComposite;
import org.jfree.ui.RectangleInsets;

/**
 * chaonan
 * 动态图表例
 */
public class SWTTimeSeries
{


    private static  TimeSeriesCollection dataset = new TimeSeriesCollection();
    private static MyMap dataMp=new MyMap();
    private static MyMap dataMp1=new MyMap();
    private static  TimeSeries s1 = new TimeSeries("cpu", Second.class);
    private static  TimeSeries s2 = new TimeSeries("Ram", Second.class);


     /**
     * Creates a chart.
     * 
     * @param dataset  a dataset.
     * 
     * @return A chart.
     */
    private static JFreeChart createChart(XYDataset dataset) {

        JFreeChart chart = ChartFactory.createTimeSeriesChart(
            "resourceuse",  // title
            "time",             // x-axis label
            "use",   // y-axis label
            dataset,            // data
            true,               // create legend?
            true,               // generate tooltips?
            false               // generate URLs?
        );

        chart.setBackgroundPaint(Color.white);


        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);
        plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        plot.setDomainCrosshairVisible(true);
        plot.setRangeCrosshairVisible(true);
        plot.getRangeAxis().setUpperBound(100);  
        XYItemRenderer r = plot.getRenderer();
        if (r instanceof XYLineAndShapeRenderer) {
            XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
            renderer.setBaseShapesVisible(true);
            renderer.setBaseShapesFilled(true);
        }

        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setDateFormatOverride(new SimpleDateFormat("mm:ss"));

        return chart;

    }

    /**
     * Creates a dataset, consisting of two series of monthly data.
     *
     * @return The dataset.
     */
    private static XYDataset addToDataset() {//更新数据
        Random r=new Random();//随机数

        dataMp.put(new Second(),20+ r.nextInt(50));
        dataMp1.put(new Second(), 20+ r.nextInt(50));
        //cpuList.add(cpuuse);
        s1.clear();
        s2.clear();
        for(Entry<Second,Integer> e:dataMp.entrySet() ){
            s1.add(e.getKey(),e.getValue());
        }
        for(Entry<Second,Integer> e:dataMp1.entrySet() ){
            s2.add(e.getKey(),e.getValue());
        }

        dataset.removeAllSeries();
        dataset.addSeries(s1);
        dataset.addSeries(s2);

        return dataset;
    }


    /**
     * Starting point for the demonstration application.
     *
     * @param args  ignored.
     */
    public static void main(String[] args) {



        final JFreeChart chart = createChart(dataset);
        final Display display = new Display();
        Shell shlCpu = new Shell(display);
        shlCpu.setSize(655, 487);
        shlCpu.setText("cpu\u4F7F\u7528\u60C5\u51B5");
        shlCpu.setLayout(new FillLayout(SWT.HORIZONTAL));

        SashForm sashForm = new SashForm(shlCpu, SWT.NONE);

        Composite composite = new Composite(sashForm, SWT.NONE);

        Button button = new Button(composite, SWT.NONE);
        button.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(SelectionEvent e) {
                new Thread(new Runnable() {

                    public void run() {
                        while (true) {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {

                                e.printStackTrace();
                            }
                            Display.getDefault().asyncExec(new Runnable() {

                                public void run() {
//                                  GetLinuxInfo service = new GetLinuxInfoImpl();
//                                  InfoData dataInfo = null;
//                                  try {
////                                        dataInfo = service.getInfo();
//                                  } catch (Exception e) {
//                                      // TODO Auto-generated catch block
//                                      e.printStackTrace();
//                                  }
                                    addToDataset();

                                    //System.out.println(dataInfo.getCpu().getCpuTotalUse());
                                }

                            });

                        }

                    }
                }).start();
            }
        });
        button.setBounds(27, 44, 98, 30);
        button.setText("启动");

        Composite composite_1 = new Composite(sashForm, SWT.NONE);
        composite_1.setLayout(new FillLayout(SWT.HORIZONTAL));
        ChartComposite frame = new ChartComposite(composite_1, SWT.NONE, chart, true);
        frame.setDisplayToolTips(true);
        frame.setHorizontalAxisTrace(false);
        frame.setVerticalAxisTrace(false);
        sashForm.setWeights(new int[] {171, 287});
        shlCpu.open();


        while (!shlCpu.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

swt动态图表实例

标签:swt动态图表   jfreechart   

原文地址:http://blog.csdn.net/q5841818/article/details/46697207

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!