|
|
Home
105 > Computers & Internet> Programming > Java |
|
|
Java2D An Introduction and Tutorial |
In Java 1.2, the paintComponent method is supplied with a Graphics2D
object (a subclass of Graphics), which contains a much richer set of
drawing operations. It includes pen widths, dashed lines, image and
gradient color fill patterns, the use of arbitrary local fonts, a
floating point coordinate system, and a number of coordinate
transformation operations. However, to maintain compatibility with
Swing as used in Java 1.1, the declared type of the paintComponent
argument is Graphics, so you have to cast it to Graphics2D before using
it. Java 1.1 | | Java 1.2 | public void paint(Graphics g) { // Set pen parameters g.setColor(someColor); g.setFont(someLimitedFont); // Draw a shape g.drawString(...); g.drawLine(...) g.drawRect(...); // outline g.fillRect(...); // solid g.drawPolygon(...); // outline g.fillPolygon(...); // solid g.drawOval(...); // outline g.fillOval(...); // solid ... } | | public void paintComponent(Graphics g) { // Clear off-screen bitmap super.paintComponent(g); // Cast Graphics to Graphics2D Graphics2D g2d = (Graphics2D)g; // Set pen parameters g2d.setPaint(fillColorOrPattern); g2d.setStroke(penThicknessOrPattern); g2d.setComposite(someAlphaComposite); g2d.setFont(anyFont); g2d.translate(...); g2d.rotate(...); g2d.scale(...); g2d.shear(...); g2d.setTransform(someAffineTransform); // Allocate a shape SomeShape s = new SomeShape(...); // Draw shape g2d.draw(s); // outline g2d.fill(s); // solid } | - Colors and patterns: gradient fills, fill patterns from tiled images, transparency
- Local fonts
- Pen thicknesses, dashing patterns, and segment connection styles
- Coordinate transformations
- Cast the Graphics object to a Graphics2D object
public void paintComponent(Graphics g) { super.paintComponent(g); // Typical Swing approach Graphics2D g2d = (Graphics2D)g; g2d.doSomeStuff(...); ... } - Create a Shape object
Rectangle2D.Double rect = ...; Ellipse2D.Double ellipse = ...; Polygon poly = ...; GeneralPath path = ...; SomeShapeYouDefined shape = ...; // Satisfies Shape interface ... - Optional: modify drawing parameters
g2d.setPaint(fillColorOrPattern); g2d.setStroke(penThicknessOrPattern); g2d.setComposite(someAlphaComposite); g2d.setFont(someFont); g2d.translate(...); g2d.rotate(...); g2d.scale(...); g2d.shear(...); g2d.setTransform(someAffineTransform); - Draw an outlined or solid version of the Shape
g2d.draw(someShape); g2d.fill(someShape); Read More
|
|
|
Additional
Info |
|
|
No.
|
245 |
Posted
on |
8 June, 2006 |
|
|
|
|
|
|
|
|
Bookmark This Page
|
Link to us from your website or blog by using the code below in your html
|
|
|
|
|
|
|