This example shows how a simple static chart can be created using the JChart2D package. It is based on the MinimalStaticChart example of the JChart2D documentation, but shows off a few more possibilities of the package, like working with colors and grids, and writing a chart to a file.
import java.awt.image.BufferedImage;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import info.monitorenter.gui.chart.Chart2D;
import info.monitorenter.gui.chart.IAxis;
import info.monitorenter.gui.chart.ITrace2D;
import info.monitorenter.gui.chart.traces.Trace2DSimple;
public class JChart2DDemo
{
Chart2D chart;
public static void main (String[] args)
{
JChart2DDemo myDemo = new JChart2DDemo();
myDemo.staticDemo();
}
public void staticDemo()
{
chart = new Chart2D();
chart.setBackground(Color.WHITE);
chart.setForeground(Color.BLUE);
chart.setGridColor(Color.GREEN);
ITrace2D trace = new Trace2DSimple();
trace.setColor(Color.RED);
trace.setName("Static Demo");
IAxis axisX = chart.getAxisX();
axisX.setPaintGrid(true);
IAxis axisY = chart.getAxisY();
axisY.setPaintGrid(true);
Random random = new Random();
for (int i=100; i>=0; i--)
{
trace.addPoint(i, random.nextDouble()*10.0+i);
}
chart.addTrace(trace);
JFrame frame = new JFrame("MinimalStaticChart");
frame.getContentPane().add(chart);
frame.setSize(400, 300);
frame.addWindowListener(
new WindowAdapter()
{
public void windowClosing (WindowEvent e)
{
try
{
BufferedImage bi = chart.snapShot();
ImageIO.write(bi, "JPEG", new File("chart.jpg"));
} catch (Exception ex)
{
System.err.println("couldn't write chart to file: "+ex.getMessage());
}
System.exit(0);
}
}
);
frame.show();
}
}
OtherOpenSourceProjectsFaq CategoryCodeSamples CodeBarn
|