JFreeChart生成动态折线图

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class RealTimeChart extends ChartPanel implements Runnable {

    private static final long serialVersionUID = 1L;
    private static TimeSeries timeSeries;

    public RealTimeChart(String chartContent, String title, String yAxisName) {
        super(createChart(chartContent, title, yAxisName));
    }

    private static JFreeChart createChart(String chartContent, String title, String yAxisName) {
        timeSeries = new TimeSeries(chartContent);
        TimeSeriesCollection timeseriescollection = new TimeSeriesCollection(timeSeries);
        JFreeChart jfreechart = ChartFactory.createTimeSeriesChart(title, "时间(秒)", yAxisName, timeseriescollection, true, true, false);
        ValueAxis valueaxis = jfreechart.getXYPlot().getDomainAxis();
        valueaxis.setAutoRange(true);
        valueaxis.setFixedAutoRange(30000D);
        return jfreechart;
    }

    @Override
    public void run() {
        while (true) {
            try {
                timeSeries.add(new Millisecond(), Math.random() * 100);
                Thread.sleep(300);
            } catch (InterruptedException e) {
            }
        }
    }

    public static void main(String[] args) {
        // 设置显示样式,避免中文乱码
        StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
        standardChartTheme.setExtraLargeFont(new Font("微软雅黑", Font.BOLD, 20));
        standardChartTheme.setRegularFont(new Font("微软雅黑", Font.PLAIN, 15));
        standardChartTheme.setLargeFont(new Font("微软雅黑", Font.PLAIN, 15));
        ChartFactory.setChartTheme(standardChartTheme);
        JFrame frame = new JFrame("折线图示例");
        RealTimeChart realTimeChart = new RealTimeChart("随机数折线图", "随机数", "数值");
        frame.getContentPane().add(realTimeChart, new BorderLayout().CENTER);
        frame.pack();
        frame.setVisible(true);
        (new Thread(realTimeChart)).start();
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent windowevent) {
                System.exit(0);
            }
        });
    }
}





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值