Code: Select all
package DynamicLineAndTimeSeriesChart;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleAnchor;
import org.jfree.ui.RefineryUtilities;
import org.jfree.ui.TextAnchor;
public class java extends ApplicationFrame implements ActionListener {
private TimeSeries series;
public String den;
private double lastValue = 100.0;
private Timer timer = new Timer(500, this);
public java(final String title) {
super(title);
this.series = new TimeSeries("Randommm Data", Millisecond.class);
final TimeSeriesCollection dataset = new TimeSeriesCollection(this.series);
final JFreeChart chart = createChart(dataset);
timer.setInitialDelay(1000);
chart.setBackgroundPaint(Color.LIGHT_GRAY);
final JPanel content = new JPanel(new BorderLayout());
final ChartPanel chartPanel = new ChartPanel(chart);
content.add(chartPanel);
//chartPanel.setPreferredSize(new java.awt.Dimension(800, 500));
setContentPane(content);
timer.start();
}
@Override
public void actionPerformed(final ActionEvent e) {
final double factor = 0.9 + 0.2*Math.random();
this.lastValue = this.lastValue * factor;
final Millisecond now = new Millisecond();
this.series.add(new Millisecond(), this.lastValue);
den = String.valueOf(lastValue);
System.out.println("Current Time in Milliseconds = " + now.toString()+", Current Value : "+this.lastValue);
}
private JFreeChart createChart(final XYDataset dataset) {
final JFreeChart result = ChartFactory.createTimeSeriesChart(
"DLaTSChart",
"Time",
"Value",
dataset,
true,
true,
false
);
final XYPlot plot = result.getXYPlot();
ValueMarker marker= new ValueMarker(85);
marker.setLabel(""+ den +"");
marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
marker.setLabelAnchor(RectangleAnchor.RIGHT);
marker.setPaint(Color.ORANGE);
plot.addRangeMarker(marker);
plot.setBackgroundPaint(new Color(0xffffe0));
plot.setDomainGridlinesVisible(true);
plot.setDomainGridlinePaint(Color.lightGray);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.lightGray);
ValueAxis xaxis = plot.getDomainAxis();
xaxis.setAutoRange(true);
xaxis.setFixedAutoRange(60000.0);
xaxis.setVerticalTickLabels(true);
ValueAxis yaxis = plot.getRangeAxis();
//yaxis.setRange(0.0, 300.0);
yaxis.setAutoRange(true);
return result;
}
public static void main(final String[] args) {
final java demo = new java("DLATSChart");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}