我使用JFreeChart创建了一个实时图表,它每隔10秒显示一个位置的温度。但是在x轴上,它显示每个温度的秒而不是当前时间(例如19:45)。如何在x轴上显示当前时间?
以下是我的代码example:
public class DynamicTimeSeriesChart extends JPanel {
TestWeatherTimeLapseService getTemp = new TestWeatherTimeLapseService(); //gets temperature
private final DynamicTimeSeriesCollection dataset;
private final JFreeChart chart;
public DynamicTimeSeriesChart(final String title) {
dataset = new DynamicTimeSeriesCollection(1, 10000, new Second());
Date date = new Date();
dataset.setTimeBase(new Second(date));
dataset.addSeries(new float[1], 0, title);
chart = ChartFactory.createTimeSeriesChart(
title, "Time", title, dataset, true, true, false);
final XYPlot plot = chart.getXYPlot();
DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setFixedAutoRange(10000);
axis.setDateFormatOverride(new SimpleDateFormat("ss.SS"));
final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setMouseWheelEnabled(true);
add(chartPanel);
chart.getXYPlot().setDomainPannable(true);
}
public void update() {
float[] newData = new float[1];
String currTemperature="";
try {
currTemperature=getTemp.getWeatherData("Laverton")[1]; //get temperature of laverton
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
float number = Float.parseFloat(currTemperature);
dataset.advanceTime();
newData[0] = number;
dataset.appendData(newData);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final DynamicTimeSeriesChart chart
= new DynamicTimeSeriesChart("Temperature");
frame.add(chart);
frame.pack();
Timer timer = new Timer(10000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
chart.update();
}
});
timer.start();
frame.setVisible(true);
}
});
}}
答案 0 :(得分:1)
您已DateAxis
SimpleDateFormat
覆盖"ss.SS"
,其中显示seconds.milliseconds
。您可能需要hour:minutes:seconds
:
axis.setDateFormatOverride(new SimpleDateFormat("HH:mm.ss"));