Crionics LOGO

TUTORIALS

 

 How to use Creator: Using existing Java2D components

As easy as 1, 2, 3...

 

Introduction

In this tutorial we will see how we can use existing Java2D components in a page. After all, it seems common nowadays to have charts and/or barcodes in a document. 

For the purpose of this tutorial we will be using two free packages:

  1. Krysalis JCharts (v1.0-cvs)
  2. Barbecue

While other charts and barcodes tools are available, we selected these because they are simple to use, are free and do not depend on extra libraries - which makes them easy to bundle with any distribution.

The problem is, when you use a component developed by third party you don't really know how it is programmed or how it can be graphically rearranged. But Java2D comes to the rescue:

  1. First, you can create a copy of the current graphic context by calling the method create(). This new context is independent from its parent and it won't affect it.
  2. Second, using Affine Transformations you can translate, rotate, scale or shear the vector space in order to rearrange the component graphical representation.

Let's put these words in pratice in section 2.

 

The code

For this example, we won't focus on how the charts and barcodes are generated but on how they are composed together.

Note how the graphic contexts are created/disposed and rearranged for each component rendering.

public static void main(String args[]) throws Exception
{
// Create the document, the page and get its dimensions
PdfDocument doc = new PdfDocument();
Page page=Page.createInstance(doc);
PageFormat pf=page.getPageFormat();

int page_x=(int)pf.getWidth();
int page_y=(int)pf.getHeight();

// Get the pencil:
Graphics2D graphics=page.getGraphics();

// Draw the area chart:
Graphics2D g2d = (Graphics2D) graphics.create();
Chart chart2 = getAreaChartVerticalLabels(page_x, page_y);
chart2.setGraphics2D(g2d);
chart2.render();
g2d.dispose();

// Draw the 3D pie with a different transparency setting:
g2d = (Graphics2D) graphics.create();
Chart chart = getChartPie3D(page_x, page_y / 2);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7F));
g2d.translate(page_x / 4, page_y / 2);
g2d.scale(0.7, 0.7);
chart.setGraphics2D(g2d);
chart.render();
g2d.dispose();

// Draw the barcode:
g2d = (Graphics2D) graphics.create();
Barcode barcode = BarcodeFactory.createCode128B("123 MyBarcode");
g2d.translate(20, page_y - (barcode.getHeight() * 0.7));
g2d.scale(0.5, 0.5);
barcode.draw(g2d, 0, 0);
g2d.dispose();

graphics.dispose();
doc.saveAs("SimpleJava2DComponentsDemo.pdf");
doc.close();
}

 

The result

Click here to display the generated file.


© 2000-2007 Crionics Inc. Report issues with this page