在设计基于C/S的客户端时,swt通常是首选。但是jfreechart的时序图(timeserial)是基于swing来实现的,要想在swt中的composite上实现,还需要进行SWT_AWT转换。
直接上代码:
1、初始化
<span style="font-size:18px;"><span style="white-space:pre"> </span>compositedyn=new Composite(shell, SWT.EMBEDDED);
compositedyn.setBounds(29, 57, 884, 513);
compositedyn.setLayout(new GridLayout(1, false));
timeseries = new TimeSeries("信号值", Millisecond.class);
datasetdyn = new TimeSeriesCollection(timeseries);
dynchartPanel = new ChartPanel(createdynChart(datasetdyn));
framedyn = SWT_AWT.new_Frame(compositedyn); //间接的的方法实现
framedyn.setLayout(new BorderLayout());
framedyn.add(dynchartPanel, BorderLayout.CENTER);</span>
2、创建freechart
<span style="font-size: 24px;"> </span><span style="font-size:18px;">private JFreeChart createdynChart(XYDataset dataset) {
JFreeChart result = ChartFactory.createTimeSeriesChart(ID+"谐波分析", "时间/min",
"电压/V", dataset, true, true, false);
System.out.println(ID);
XYPlot plot = (XYPlot) result.getPlot();
ValueAxis axis = plot.getDomainAxis(); //横坐标的文字
ValueAxis caxis = plot.getRangeAxis();//纵坐标
//axis.setAutoTickUnitSelection(false);
TextTitle textTitle = result.getTitle();
textTitle.setFont(DEFAULT_TITLE_FONT);
caxis.setLabelFont(DEFAULT_TITLE_FONT);
axis.setLabelFont(DEFAULT_TITLE_FONT);
result.getLegend().setItemFont(DEFAULT_TITLE_FONT);
axis.setInverted(true);
// axis.setPositiveArrowVisible(true);
//axis.setAutoRange(true);
//axis.setVerticalTickLabels(true);
axis.setFixedAutoRange(50*60000.0); //6s*n
axis = plot.getRangeAxis();
axis.setRange(0.0, 150.0); //纵坐标的范围
//axis.setVisible(true);
return result; //返回的是图标的格式
}</span>
3、在ui界面下另开线程向时序图发数据
<span style="font-size:18px;">
</span><pre name="code" class="java"><span style="font-size:18px;"><strong>new Thread() {
public void run() {
// 此处为另外一个单独线程,非UI线程
while(true) {
// 非UI线程访问UI
display.asyncExec(new Runnable() {
@Override
public void run() {
double factor = 0.90 + 0.2 * Math.random();
lastValue = lastValue * factor;
Millisecond now = new Millisecond();
timeseries.add(now, lastValue);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}.start();</strong></span>