本文主要给大家介绍如何使用ChartDirector创建单独的Java应用。在创建程序之前看是否已经下载了该控件,并且配置好了相应的Java IDE开发环境。使用ChartDirector控件创建图表
本文主要给大家介绍如何使用ChartDirector创建单独的Java应用。在创建程序之前看是否已经下载了该控件,并且配置好了相应的Java IDE开发环境。使用ChartDirector控件创建图表相对简单,控件提供了完善的API以及事例和帮助文档,开发人员可以轻松上手。
>>最新版ChartDirector v6.0下载
这里我也尝试用ChartDirector免费版画了一张图表(图下),只是在图表下方会出现一根黄条,有碍美观,不建议使用。
在利用该控件创建Java图表应用程序之前,应该大致了解该控件创建图表的大致过程以及使用到的相关函数,我们大致介绍下该事例中将要使用到的API:
- 要创建图表,首先得利用控件提供的API来创建图表对象,本文中咱们要创建柱状图,需要用到 XYChart对象,该对象适用于有Y轴和X轴的图表,250x250是图表区域的大小:XYChart c = new XYChart(250, 250);
- 第二步主要设置柱状图显示区域的大小以及坐标等,因为第一步已经设置了在250x250区域内绘制图表,由于图表还有X和Y轴以及轴标签和图例等,图表的实际区域应该小于250x250:c.setPlotArea(30, 20, 200, 200);
- 通过c.addBarLayer(data);来添加一个柱状图到绘制区域,因为ChartDirector支持多种图表组合显示,可以为绘制区域添加多个图表层。其中Data是图表的数据
- 接下来主要就对图表的X,Y轴进行相应的设置和格式化等
- 最后使用ChartViewer控件来显示图表:viewer.setChart(c);
完整的代码如下:
import java.awt.*;import java.awt.event.*;import javax.swing.*;import ChartDirector.*; public class simplebar implements DemoModule{ //Name of demo program public String toString() { return "Simple Bar Chart (1)"; } //Number of charts produced in this demo public int getNoOfCharts() { return 1; } //Main code for creating charts public void createChart(ChartViewer viewer, int chartIndex) { // The data for the bar chart double[] data = {85, 156, 179.5, 211, 123}; // The labels for the bar chart String[] labels = {"Mon", "Tue", "Wed", "Thu", "Fri"}; // Create a XYChart object of size 250 x 250 pixels XYChart c = new XYChart(250, 250); // Set the plotarea at (30, 20) and of size 200 x 200 pixels c.setPlotArea(30, 20, 200, 200); // Add a bar chart layer using the given data c.addBarLayer(data); // Set the labels on the x axis. c.xAxis().setLabels(labels); // Output the chart viewer.setChart(c); //include tool tip for the chart viewer.setImageMap(c.getHTMLImageMap("clickable", "", "title='{xLabel}: {value} GBytes'")); } //Allow this module to run as standalone program for easy testing public static void main(String[] args) { //Instantiate an instance of this demo module DemoModule demo = new simplebar(); //Create and set up the main window JFrame frame = new JFrame(demo.toString()); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); frame.getContentPane().setBackground(Color.white); // Create the chart and put them in the content pane ChartViewer viewer = new ChartViewer(); demo.createChart(viewer, 0); frame.getContentPane().add(viewer); // Display the window frame.pack(); frame.setVisible(true); }}