Java 2D and SVG
Rachel Struthers
Topics Covered
Java 2D
Rendering
Basic Shapes
Transformations
SVG(Scalable Vector Graphics)
Basic drawing commands
Some examples
Batik Java library
Java 2D and SVG
Vector based rather than pixel based
Both can be used on the web to show
high-quality interactive graphcis
Java 2D – produce vector graphics using
code
API in Java 1.2 and above
SVG – produce vector graphics using XML
Vector Graphics vs. Raster
Graphics
Raster Graphics
Pixel based – high bandwidth
Resolution dependent, picture from workstation might
not work on PDA
Examples: GIF, JPEG, BMP
Vector Graphics
Command based – low bandwidth
Resolution independent = scalable, zoomable without
loss of quality
Examples: SVG, SWF (Flash), EPS (Encapsulated
Postscript)
What is Java 2D?
API included with JDK
Line art
Text
Imaging
Allows you to easily
Draw lines of any thickness
Fill shapes with gradients and textures
Move, rotate, scale, and shear text and graphics
Composite overlapping text and graphics
Example: ShowOff.java (from Java 2D book)
Where Can I Use Java 2D?
Any Java 2 type application
Included in Java 1.2 or above
Stand-alone rich-client applications
Web applications (applets)
Servers side generation of dynamic
images suchs as maps, charts, etc.
What Are Prerequisites for
Using?
Basic Java programming
Some OO knowledge
Need to have basic grasp of interfaces for:
Shape
Paint
Some exposure to graphics or user interface
programing helpful
AWT or Swing
Graphics in other languages
Think Paint!
When using Java 2D, keep in mind the
rendering pipeline
Nothing is shown until paint is called
Must extend an object that is of the
Component family
Override paint() method
No painting – no picture!
When is paint() called for a
component?
System triggered:
When the component is first shown
When it is “damaged” (covered by a window
and then uncovered, for example)
Component resized
App triggered:
When a program calls repaint
State of button has changed
Date (model) has changed
Paint in Swing or AWT
Components
For AWT, can override Canvas, Panel
paint methods
Other things that inherit from Component
For Swing
Extend JPanel, JButton, etc
Other things that inherit from JComponent
How to use in AWT
Extend a component such as Canvas or Panel
Override
public void paint(Graphics g)
If extending a container call super.paint(g) so
that children are painted
Rest of the discussion uses Swing components
How to use in Swing
Components
Extend a Swing component such as JPanel
Override paintComponent
Cast Graphics to Graphics2D so you can use
advanced features
Make sure you call super.paintComponent(g)
as first call!
Or funny things happen
Ghosts, background wrong
Methods Called for Swing
Refresh
In Swing paint() still gets called when it's time
to render
Work of paint is divided into three methods
protected void paintComponent(Graphics g)
protected void paintBorder(Graphics g)
protected void paintChildren(Graphics g)
Generally you only override paintComponent
Basic Java 2D
public MyBasicDrawPanel extends JPanel {
protected void paintComponent(Graphics g)
{
// Call super.paintComponent!
super.paintComponent(g);
// Cast Graphics to Graphics2D
Graphics2D g2d = (Graphics2D)g;
// Draw
g2d.setColor(Color.blue);
g2d.fillRect(20, 20, 100, 80);
}
}
Not restricted to JPanel!
Can also use in JButton, JLabel
Custom renderers for
JTable
JComboBox
Etc.
Painting Tips
Be polite: trigger a repaint (as when data model
changes) by calling repaint not paint
Puts a request in the event queue
If drawing is complex, try to repaint only the
area that needs updating
Use void repaint(Rectangle r) not
void repaint() (paints the whole thing)
For paintComponent method, always call
super.paintComponent first!
Make use of clipping to enhance performance
Graphics2D object
Java 2D's extension of Graphics object
Used to draw Shape objects
Has rendering attributes:
Pen Style (solid, dotted, dashed)
Fill
Compositing (used when objects overlap)
Transform (scale, rotate, translate, shear)
Clip area
Font
Rendering hints
Graphics2D – setting attributes
setStroke
setPaint
setComposite
setTransform
setClip
setFont
setRenderingHints
Graphics2D Rendering
Methods
draw
renders outline of graphics primitive using stroke
and paint attributes
fill
fills shape with given paint attribute (color or
pattern)
drawString
draw string with given font and paint attribute
drawImage
draw an image
Shape Interface
To draw, use things that implement Shape such as:
Area
CubicCurve2D
GeneralPath
Line2D
Polygon
QuadCurve2D
Rectangle
RectangularShape
These use double's or float's for parameters
Drawing Shapes
Old AWT way (can still use)
drawXxxx
fillXxxx
OR - Create a Shape object and the draw
or fill
Creating Shapes
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
// Assume x, y, and diameter are instance
variables
Ellipse2D.Double circle =
new Ellipse2D.double(x, y, diameter, diameter);
g2d.fill(circle);
}
Graphics2D draw and fill
Arguments to the draw and fill must
implement the Shape interface
Graphics built using objects rather than
instructions
Rectangles, Ellipses and ARcs
Note that many Shape classes have inner
constructors
Use Rectangle2D inner classes to create:
Rectangle2D.Double
Retangle2D.Float
Ellipse2D:
Ellipse2D.Double
Ellipse2D.Float
Arc2D
Arc2D.Double
Arc2D.Float
See JavaApplet2D.java
Arc2D – three different close
types
Open
Pie
Chord
Lines
Create a line using Line2D classes inner class
constructors
Line2D.Float(), etc.
Line2D.Double(), etc.
StringArt.java
QuadCurve2D
2 end points and a control points
CubicCurve2D
2 end points and 2 control points
DragKing.java
Bounds/Hit Testing
Shape has various contains() methods
Makes for easy user interaction
Java2DApplet.java
public void mouseClicked(MouseEvent e)
{
Point2D point = new Point2D.Double(e.getX(), e.getY());
if (shape.contains(point))
{
showMessage(“Hit me!”);
}
}
Combining Shapes
Combine Shape objects using the Area class
Area implements Shape – can draw using
Graphics2D
Create: new Area() or new Area(Shape s)
Combine:
public void add(Area a)
public void intersect(Area a);
public void subtract(Area a);
public void exclusiveOr(Area a);
CombiningShapes.java
Painting
Paint attribute of Graphics2D
Goes way beyond the old color attribute
(still useable)
getPaint, setPaint
Used when fill method is called on a shape
Arguments to setPaint must implement the
Paint interface
PaintingAndStroking.java
Paint Classes
Color
Solid color
Same constants as in AWT: Color.red, Color.black, etc.
Java2DApplet.java
GradientPaint
Gradient fill gradually combining two colors
Can create your own
RoundGradientPaint.java
TexturePaint
Tiled image
TexturePaintFill.java
Compositing
Process of putting two pictures together
Every time object is drawn, source and
destination combination process is
performed
Usually use source over destination
Compositing Rules
Transparency
Assign transparency (alpha) values to
drawing operations
Underlying graphics show through
Call setComposite of Graphics2D object
AlphaComposite.getInstance
TransparencyExample.java (run-
transparency)
Using Local Fonts
Same logical fonts as in Java 1.1
Serif, SansSerif, Monospaced, Dialog,
DialogInput
Also, arbitrary local fonts
Must lookup entire list
May take awhile
Use GraphicsEnvironment methods
getAvailableFontFamilyNames
getAllFonts
Printing All Font Names
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = env.getAvailableFontFamilyName();
System.out.println("Available Fonts:");
for(int i=0; i<fontNames.length; i++)
System.out.println(" " + fontNames[i]);
Drawing With Local Fonts -
Example
Query the available fonts using
getAvailableFontNames of
GraphicsEnvironment
Set the font in the Graphcis2D object
Call g2d.drawString method
ShowFonts.java
Stroke Styles in Java 2D
In AWT, could only do 1-pixel wide lines, no
control over how lines are joined
Much more flexibility in Java2D – can specify:
Pen thickness
Dashing pattern
The way line segments are joined together
Create a BasicStroke object (several
contructors)
StrokePanel.java (Java2DApplet.java)
Coordinate Transformations
Java 2D allows you to easily
Translate
Rotate
Scale
Shear
Use java.awt.geom.AffineTransform
Example from Java 2D book: Transformers.java
and other classes
Creates a GeneralPath object
Transform using the above operations
Other Capabilities of Java 2D
High-quality printing
Improved XOR mode
Custom color mixing
Fancy text operations
Low-level image processing
See JavaWorld article:
http://www.javaworld.com/javaworld/jw-09-1998/jw-09-
media.html (download\media\run.bat)
Animation -see example programs:
TextBouncer
Bouncer
For More Information
Sun's page:
http://java.sun.com/products/java-
media/2D/
Many of the examples were from this
book:
Java 2D Graphics by Jonathan Knudsen
Examples From Java SDK
Look in:
C:\j2sdk1.4.1_02\demo\jfc\Java2D
Open Java2Demo.html
Source is included
JFreeChart
Example of someone using Java2D API
Open source Java API
For creating charts and graphs
Has example of generating chart in servlet
Also has demo that shows several different
kinds of charts
jfreechart-0.9.14-demo.jar
https://sourceforge.net/projects/jfreechart/
What is SVG?
Scalable Vector Graphics
Language for describing two-dimensioal
graphics and graphical applications in XML
Created by the World Wide Web Consortium
(W3C)
Over 20 organizations including Sun
Microsystems, Adobe, Apple and IBM involved
Sun active from the start
SVG Features
Plain text format (not some complicated binary
form)
Low band-width
Scalable – unlike GIF and JPEG
Zoomable – picture just as clear
Searchable and selectable text (unlike bitmaps)
Scripting and animation
Works with Java!
Open Standard
True XML
SVG on the Web
Can easily be generated on web servers
“on the fly”
Example: create a high quality, low
bandwith stock quote graph
SVG can be created:
Through a drawing package
Or by writing code
Or Notepad
How to View
Adobe plugin:
http://www.adobe.com/svg/viewer/install/
Small and powerful
Many examles on their website
SVG Tag Sampling
Shape Tags: <line>, <rect>, <circle>, <ellipse>, <polyline>,
<polygon>, <path>
Paint Tags: <linearGradient>, <radialGradient>, <pattern>,
<mask>
Text Tags: <text>, <tspan>, <textPath>, <font>, <font-face>,
<glyph>
Filter Tags: <filter>, <feBlend>, <feFlood>, <feColorMatrix>,
<feGaussianBlur> <feMorphology> <feSpotLight>
Animation Tags: <animate>, <animateMotion>,
<animateTransform>, <animateColor>, <set>
Misc Tags: <image>, <symbol>, <g>, <defs>, <use>
And Much More
SVG in Action
<svg>
<g style="fill-opacity:0.7; stroke:black; stroke-
width:0.1cm;">
<circle cx="6cm" cy="2cm" r="100" style="fill:red;"
transform="translate(0,50)" />
<circle cx="6cm" cy="2cm" r="100"
style="fill:blue;" transform="translate(70,150)" />
<circle cx="6cm" cy="2cm" r="100"
style="fill:green;" transform="translate(-70,150)"/>
</g>
</svg>
Filter Effects
Line Drawing Example
Basic SVG Shapes
<line x1="start-x" y1="start-y" x2="end-x" y2="end-y" />
<rect x="left-x" y="top-y" width="width" height="height"
/>
<circle cx="center-x" cy="center-y" r="radius" />
<ellipse cx="center-x" cy="center-y" rx="x-radius"
ry="y-radius" />
<polygon points="points" />
<polyline points="points" />
Line Example
Fancy SVG Examples
From kevlindev.com:
Kaleidoscope
carto.net
Weather map
Fireworks
Animated bus track
Canvas and Layers
Batik
Open source Java API from Apache:
http://xml.apache.org/batik/index.html
Render SVG files in Java application
Write Java 2D to SVG file
Batik Application Modules
SVG Browser
View, zoom, pan an rotate SVG documents
SVG Pretty Printer
Tidy up messay SVG
SVG Font Converter
Convert from True Type to SVG font format
SVG Rasterizer
Convert to and from SVG content
SVG Browser - Squiggle
Java program included in Batik release
batik-squiggle.jar
If Java installed – simple double-click to run
Allows you to view SVG files – zoom, search
text
View many sample SVG files that come with
Batik
sizeofsun – search for Pluto
Batik Core Modules
SVG Generator
SVGCanvas2D
Java 2D “draws” to an SVG file
SVG DOM
Manipulate SVG documents in a Java program
JSVGCanvas
Display SVG content in a Java panel
Transcoder
Save SVG in another format (such as JPEG)
JSVG Canvas
Use to display SVG in a Java program
JSVGCanvasExample.java
JSVGCanvas canvas = new JSVGCanvas();
canvas.setURI( new
File(fileName).toURL().toString() );
SVG Generator
Write any arbitray Java 2D graphics to
SVG
Can then view in browser with SVG
plugin
Uses SVGGraphics2D
Similar to Grahpics2D in Java 2D
Write to an XML file instead of printer or
screen
SVG – More Information
http://www.kevlindev.com/
Tutorials
Examples
Batik
http://xml.apache.org/batik/index.html
Adobe SVG Zone
http://www.adobe.com/svg/main.html
Browser plugin
Examples
SVG Specification
http://www.w3.org/TR/SVG/