JFreeChart

清浅清浅發表於2024-05-30

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);
        }
    });
}

}