创建一个动态曲线图JFreechar对象
时间: 2024-01-03 17:03:42 浏览: 83
好的,以下是在Java中创建动态曲线图JFreeChart对象的示例代码:
```java
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.XYPlot;
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 javax.swing.*;
import java.awt.*;
public class DynamicLineChart extends JFrame {
private TimeSeries series;
public DynamicLineChart(String title) {
super(title);
series = new TimeSeries("Random Data");
TimeSeriesCollection dataset = new TimeSeriesCollection(series);
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(500, 270));
setContentPane(chartPanel);
}
private JFreeChart createChart(XYDataset dataset) {
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Dynamic Line Chart",
"Time",
"Value",
dataset,
true,
true,
false
);
XYPlot plot = chart.getXYPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
return chart;
}
public void addData(double data) {
series.add(new Second(), data);
}
public static void main(String[] args) {
DynamicLineChart chart = new DynamicLineChart("Dynamic Line Chart");
chart.pack();
RefineryUtilities.centerFrameOnScreen(chart);
chart.setVisible(true);
while (true) {
double data = Math.random() * 100;
chart.addData(data);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这个示例代码创建了一个动态曲线图,并在窗口中显示出来。通过addData方法可以向图表中添加数据,示例代码中每隔一秒钟随机生成一个数据点并添加到图表中。你可以根据你的需要对代码进行修改和扩展。
阅读全文