Java Reference
In-Depth Information
Line 25 of Fig. 13.29 casts the Graphics reference received by paintComponent to a
Graphics2D reference and assigns it to g2d to allow access to the Java 2D features.
1
// Fig. 13.29: ShapesJPanel.java
2
// Demonstrating some Java 2D shapes.
3
import java.awt.Color;
4
import java.awt.Graphics;
5
6
7
8
import java.awt.BasicStroke;
import java.awt.GradientPaint;
import java.awt.TexturePaint;
import java.awt.Rectangle;
9
10
11
12
13
14
15
16
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.geom.Arc2D;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
17
18
public class ShapesJPanel extends JPanel
19
{
20
// draw shapes with Java 2D API
21
@Override
22
public void paintComponent(Graphics g)
23
{
24
super.paintComponent(g);
25
Graphics2D g2d = (Graphics2D) g; // cast g to Graphics2D
26
27
// draw 2D ellipse filled with a blue-yellow gradient
g2d.setPaint( new GradientPaint( 5 , 30 , Color.BLUE , 35 , 100 ,
Color.YELLOW , true ));
g2d.fill( new Ellipse2D.Double( 5 , 30 , 65 , 100 ));
28
29
30
31
32
// draw 2D rectangle in red
g2d.setPaint( Color.RED );
g2d.setStroke( new BasicStroke( 10.0f ));
g2d.draw( new Rectangle2D.Double( 80 , 30 , 65 , 100 ));
33
34
35
36
37
// draw 2D rounded rectangle with a buffered background
BufferedImage buffImage = new BufferedImage( 10 , 10 ,
BufferedImage.TYPE_INT_RGB );
38
39
40
41
// obtain Graphics2D from buffImage and draw on it
42
Graphics2D gg = buffImage.createGraphics();
43
gg.setColor( Color.YELLOW );
44
gg.fillRect( 0 , 0 , 10 , 10 );
45
gg.setColor( Color.BLACK );
46
gg.drawRect( 1 , 1 , 6 , 6 );
47
gg.setColor( Color.BLUE );
48
gg.fillRect( 1 , 1 , 3 , 3 );
49
gg.setColor( Color.RED );
Fig. 13.29 | Demonstrating some Java 2D shapes. (Part 1 of 2.)
Search WWH ::




Custom Search