Graficos Y Java 2D
1 Introducción
2 Contextos y objetos gráficos
3 Colores
4 Fuentes
5 Pintar Líneas, Rectángulos y Óvalos
6 Pintar Arcos
7 Pintar Polígonos and Polilíneas
8 Java2D API
9 Ejemplo
1 Introducción
Capacidades gráficas de JAVA
− Pintar figuras de 2D
− Uso y control colores
− Uso y control de fuentes
Java 2D API
− Uso más sofisticado de primitivas de
dibujo en 2D
Uso de formar y polígonos 2D personalizados
Relleno de figuras con colores, gradientes,
patrones y texturas.
Jerarquía de algunas clases e interfaces del Java2D API.
Object
Color
Component
Font
FontMetrics
Graphics
Polygon
Clases e interfaces del Java2D API que aparecen en el
paquete [Link]
Graphics2D interface
[Link]
BasicStroke interface
[Link]
GradientPaint
interface
TexturePaint [Link]
Clases e interfaces del Java2D API que aparecen en
el paquete [Link]
GeneralPath
Line2D
RectangularShape
Arc2D
Ellipse2D
Rectangle2D
RoundRectangle2D
1 Introducción
Sistema de coordenadas de JAVA
− Identifica todos los puntos disponibles de
la pantallas
− Origen de coordenadas (0,0) en la
esquina superior izquierda
− Sistema de coordenadas compuestas por
componentes X e Y.
Sistema de coordenadas de Java. Unidad de medida en pixels.
+x
(0, 0) X a xis
(x , y )
+y
Y a xis
2 Contextos y objetos gráficos
Contexto Graphics
− Permite pintar en la pantalla.
– El objeto Graphics controla el contexto de
graficos
Controla como se pinta en la pantalla
− La Clase Graphics es abstracta
No se puede instanciar
Contribuye a la portabilidad de Java
− La el método paint de la lase Component emplea
el objeto Graphics
public void paint( Graphics g )
− Se puede invocar por medio del método repaint
3 Colores
Clase Color
− Define los métodos y las constantes para
manipular los colores.
− Los colores se crean en base al esquema
de rojo/verde/azul (RGB).
Constantes de colores definidas en la clase Color
Color constant Color RGB value
public final static Color ORANGE orange 255, 200, 0
public final static Color PINK pink 255, 175, 175
public final static Color CYAN cyan 0, 255, 255
public final static Color MAGENTA magenta 255, 0, 255
public final static Color YELLOW yellow 255, 255, 0
public final static Color BLACK black 0, 0, 0
public final static Color WHITE white 255, 255, 255
public final static Color GRAY gray 128, 128, 128
public final static Color LIGHT_GRAY light gray 192, 192, 192
public final static Color DARK_GRAY dark gray 64, 64, 64
public final static Color RED red 255, 0, 0
public final static Color GREEN green 0, 255, 0
public final static Color BLUE blue 0, 0, 255
Métodos de la clase Color y métodos de relacionados de la
clase Graphics
Method Description
Color constructors and methods
public Color( int r, int g, int b )
Creates a color based on red, green and blue components expressed as integers
from 0 to 255.
public Color( float r, float g, float b )
Creates a color based on red, green and blue components expressed as floating-
point values from 0.0 to 1.0.
public int getRed()
Returns a value between 0 and 255 representing the red content.
public int getGreen()
Returns a value between 0 and 255 representing the green content.
public int getBlue()
Returns a value between 0 and 255 representing the blue content.
Graphics methods for manipulating Colors
public Color getColor()
Returns a Color object representing the current color for the graphics context.
public void setColor( Color c )
Sets the current color for drawing with the graphics context.
1 // Fig. 12.5: [Link]
2 // Demonstrating Colors.
3 import [Link].*;
4 import [Link].*;
5
6 public class ShowColors extends JFrame {
7
8 // constructor sets window's title bar string and dimensions
9 public ShowColors()
10 {
11 super( "Using colors" ); Pinta la ventana cuando
12 comienza la ejecución de
13 setSize( 400, 130 ); la aplicación
14 setVisible( true );
15 }
16 El método setColor establece el color
17 // draw rectangles and Strings in different colors de pintura en base a un color RGB
18 public void paint( Graphics g )
19 {
20 // call superclass's paint method El método fillRect crea un
21 [Link]( g ); rectángulo relleno en el color de
22
pintura actual.
23 // set new drawing color using integers
24 [Link]( new Color( 255, 0, 0 ) );
25 [Link]( 25, 25, 100, 20 );
26 [Link]( "Current RGB: " + [Link](), 130, 40 );
27
El método drawString escribe un
String en el color actual en las
coordenadas especificadas
28 // set new drawing color using floats
29 [Link]( new Color( 0.0f, 1.0f, 0.0f ) );
30 [Link]( 25, 50, 100, 20 );
31 [Link]( "Current RGB: " + [Link](), 130, 65 );
32
33 // set new drawing color using static Color objects
34 [Link]( [Link] );
35 [Link]( 25, 75, 100, 20 );
36 [Link]( "Current RGB: " + [Link](), 130, 90 );
37
Empleamos las constantes de
38 // display individual RGB values
39 Color color = [Link];
la clase Color
40 [Link]( color );
41 [Link]( 25, 100, 100, 20 );
42 [Link]( "RGB values: " + [Link]() + ", " +
43 [Link]() + ", " + [Link](), 130, 115 );
44
45 } // end method paint
46
47 // execute application
48 public static void main( String args[] )
49 {
50 ShowColors application = new ShowColors();
51 [Link]( JFrame.EXIT_ON_CLOSE );
52 }
53
54 } // end class ShowColors
1 // Fig. 12.6: [Link]
2 // Choosing colors with JColorChooser.
3 import [Link].*;
4 import [Link].*;
5 import [Link].*;
6
7 public class ShowColors2 extends JFrame {
8 private JButton changeColorButton;
9 private Color color = Color.LIGHT_GRAY;
10 private Container container;
11
12 // set up GUI
13 public ShowColors2()
14 {
15 super( "Using JColorChooser" );
16
17 container = getContentPane();
18 [Link]( new FlowLayout() );
19
20 // set up changeColorButton and register its event handler
21 changeColorButton = new JButton( "Change Color" );
22 [Link](
23
24 new ActionListener() { // anonymous inner class
25
26 // display JColorChooser when user clicks button JColorChooser presenta
27 public void actionPerformed( ActionEvent event )
un diálogo para
28 {
29 color = [Link](
seleccionar colores
30 [Link], "Choose a color", color );
31
32 // set default color, if no color is returned
33 if ( color == null )
static showDialog
34 color = Color.LIGHT_GRAY;
35 muestra el cuadro de
36 // change content pane's background color diálogo
37 [Link]( color );
38 }
39
40 } // end anonymous inner class
41
42 ); // end call to addActionListener
43
44 [Link]( changeColorButton );
45
46 setSize( 400, 130 );
47 setVisible( true );
48
49 } // end ShowColor2 constructor
50
51 // execute application
52 public static void main( String args[] )
53 {
54 ShowColors2 application = new ShowColors2();
55 [Link]( JFrame.EXIT_ON_CLOSE );
56 }
57
58 } // end class ShowColors2
[Link]
Fig. 12.7 HSB and RGB tabs
of the JColorChooser dialog
4 Fuente
Clase Font
− Contiene métodos y constantes para el
control de las fuentes.
− El constructor de la clase Font tiene tres
argumentos
Font name
– Monospaced, SansSerif, Serif, etc.
Font style
– [Link], [Link] y [Link]
Font size
− Medido en puntos
Métodos y constantes relacionados con la clase Font
Method or constant Description
Font constants, constructors and methods for drawing polygons
public final static int PLAIN
A constant representing a plain font style.
public final static int BOLD
A constant representing a bold font style.
public final static int ITALIC
A constant representing an italic font style.
public Font( String name, int style, int size )
Creates a Font object with the specified font, style and size.
public int getStyle()
Returns an integer value indicating the current font style.
public int getSize()
Returns an integer value indicating the current font size.
public String getName()
Returns the current font name as a string.
public String getFamily()
Returns the font’s family name as a string.
public boolean isPlain()
Tests a font for a plain font style. Returns true if the font is plain.
public boolean isBold()
Tests a font for a bold font style. Returns true if the font is bold.
public boolean isItalic()
Tests a font for an italic font style. Returns true if the font is italic.
Method or constant
Description
Graphics methods for manipulating Fonts
public Font getFont()
Returns a Font object reference representing the current font.
public void setFont( Font f )
Sets the current font to the font, style and size specified by the Font
object reference f.
1 // Fig. 12.9: [Link]
2 // Using fonts.
3 import [Link].*;
4 import [Link].*;
5
6 public class Fonts extends JFrame {
7
8 // set window's title bar and dimensions
9 public Fonts()
10 {
11 super( "Using fonts" );
12
13 setSize( 420, 125 );
14 setVisible( true );
15 }
16
17 // display Strings in different fonts and colors
18 public void paint( Graphics g )
El método setFont establece la fuente a usar
19 {
20 // call superclass's paint method
21 [Link]( g );
22
23 // set font to Serif (Times), bold, 12pt and draw a string
24 [Link]( new Font( "Serif", [Link], 12 ) );
25 [Link]( "Serif 12 point bold.", 20, 50 ); Escribeel texto con la
configuración actual de
fuente
26
27 // set font to Monospaced (Courier), italic, 24pt and draw a
string
28 [Link]( new Font( "Monospaced", [Link], 24 ) );
29 [Link]( "Monospaced 24 point italic.", 20, 70 );
30
31 // set font to SansSerif (Helvetica), plain, 14pt and draw a
string
32 [Link]( new Font( "SansSerif", [Link], 14 ) );
33 [Link]( "SansSerif 14 point plain.", 20, 90 );
34
35 // set font to Serif (Times), bold/italic, 18pt and draw a
string
36 [Link]( [Link] );
37 [Link]( new Font( "Serif", [Link] + [Link], 18 ) );
38 [Link]( [Link]().getName() + " " +
[Link]().getSize() +
39 " point bold italic.", 20, 110 );
40
41 } // end method paint
42
43 // execute application
44 public static void main( String args[] )
45 {
46 Fonts application = new Fonts();
47 [Link]( JFrame.EXIT_ON_CLOSE );
48 }
49
50 } // end class Fonts
Control de fuentes
Parámetros de medida y posición de
las Fuentes
− Height - Altura
− Descent (puntos por debajo de la linea
base)
− Ascent (puntos por encima de la linea
base)
− Leading (diferencia entre Ascent y
Descent)
Control y medidas
Xy1Õ
le ading
he ight asce nt
ba seline
descent
Fig. 12.11 FontMetrics and
Graphics methods for
obtaining font metrics
Method Description
FontMetrics methods
public int getAscent()
Returns a value representing the ascent of a font in points.
public int getDescent()
Returns a value representing the descent of a font in points.
public int getLeading()
Returns a value representing the leading of a font in points.
public int getHeight()
Returns a value representing the height of a font in points.
Graphics methods for getting a Font’s FontMetrics
public FontMetrics getFontMetrics()
Returns the FontMetrics object for the current drawing Font.
public FontMetrics getFontMetrics( Font f )
Returns the FontMetrics object for the specified Font argument.
1 // Fig. 12.12: [Link]
2 // FontMetrics and Graphics [Link]
methods useful for obtaining font Line 22
metrics. Line 23
3 import [Link].*;
4 import [Link].*;
5 Set font to SansSerif 12-point bold
6 public class Metrics extends
JFrame { Obtain FontMetrics
object for current font
7
8 // set window's title bar
String and dimensions
9 public Metrics()
Use FontMetrics to
25 [Link]( "Ascent: " + obtain ascent, descent,
height and leading
[Link](), 10, 55 ); [Link]
Repeat same process for
26 [Link]( "Descent:Serif
" 14-point
Lines 25-28
italic font
+ [Link](), 10, 70 ); Lines 30-37
27 [Link]( "Height: " +
[Link](), 10, 85 );
28 [Link]( "Leading: "
+ [Link](), 10, 100 );
29
30 Font font = new
Font( "Serif", [Link], 14 );
31 metrics =
[Link]( font );
[Link]
5 Pintar Líneas, Rectángulos y Óvalos
Clase Graphics
− Provee métodos para pintar líneas,
rectángulos y óvalos
Todos lo métodos de pintar estas figuras
requieren el ancho y alto que ocuparan
Existen los métodos para pintar figuras con o
sin rellene (draw* y fill*)
Métodos de la clase Graphics para pintar líneas,
rectángulos y óvalos
Method Description
public void drawLine( int x1, int y1, int x2, int y2 )
Draws a line between the point (x1, y1) and the point (x2, y2).
public void drawRect( int x, int y, int width, int height )
Draws a rectangle of the specified width and height. The top-left corner of the
rectangle has the coordinates (x, y).
public void fillRect( int x, int y, int width, int height )
Draws a solid rectangle with the specified width and height. The top-left
corner of the rectangle has the coordinate (x, y).
public void clearRect( int x, int y, int width, int height )
Draws a solid rectangle with the specified width and height in the current
background color. The top-left corner of the rectangle has the coordinate ( x, y).
public void drawRoundRect( int x, int y, int width, int height,
int arcWidth, int arcHeight )
Draws a rectangle with rounded corners in the current color with the specified
width and height. The arcWidth and arcHeight determine the rounding of
the corners (see Fig. 12.15).
public void fillRoundRect( int x, int y, int width, int height,
int arcWidth, int arcHeight )
Draws a solid rectangle with rounded corners in the current color with the
specified width and height. The arcWidth and arcHeight determine the
rounding of the corners (see Fig. 12.15).
Métodos de la clase Graphics para pintar líneas,
rectángulos y óvalos
Method
Description
public void draw3DRect( int x, int y, int width, int height, boolean b )
Draws a three-dimensional rectangle in the current color with the specified
width and height. The top-left corner of the rectangle has the coordinates ( x,
y). The rectangle appears raised when b is true and lowered when b is false.
public void fill3DRect( int x, int y, int width, int height, boolean b )
Draws a filled three-dimensional rectangle in the current color with the specified
width and height. The top-left corner of the rectangle has the coordinates ( x,
y). The rectangle appears raised when b is true and lowered when b is false.
public void drawOval( int x, int y, int width, int height )
Draws an oval in the current color with the specified width and height. The
bounding rectangle’s top-left corner is at the coordinates ( x, y). The oval touches
all four sides of the bounding rectangle at the center of each side (see
Fig. 12.16).
public void fillOval( int x, int y, int width, int height )
Draws a filled oval in the current color with the specified width and height.
The bounding rectangle’s top-left corner is at the coordinates ( x, y). The oval
touches all four sides of the bounding rectangle at the center of each side (see
Fig. 12.16).
1 // Fig. 12.14: [Link]
2 // Drawing lines, rectangles and ovals.
3 import [Link].*;
4 import [Link].*;
5
6 public class LinesRectsOvals extends JFrame {
7
8 // set window's title bar String and dimensions
9 public LinesRectsOvals()
10 {
11 super( "Drawing lines, rectangles and ovals" );
12
13 setSize( 400, 165 );
14 setVisible( true );
15 }
16
17 // display various lines, rectangles and ovals
18 public void paint( Graphics g )
19 {
20 [Link]( g ); // call superclass's paint method
21
22 [Link]( [Link] );
23 [Link]( 5, 30, 350, 30 );
24
25 [Link]( [Link] );
26 [Link]( 5, 40, 90, 55 );
27 [Link]( 100, 40, 90, 55 );
28
29 [Link]( [Link] );
30 [Link]( 195, 40, 90, 55, 50, 50 );
Draw filled rounded rectangle
31 [Link]( 290, 40, 90, 55, 20, 20 );
32 Draw (non-filled) rounded rectangle
33 [Link]( [Link] );
34 g.draw3DRect( 5, 100, 90, 55, true ); Draw 3D rectangle
35 g.fill3DRect( 100, 100, 90, 55, false );
36 Draw filled 3D rectangle
37 [Link]( [Link] );
Draw oval
38 [Link]( 195, 100, 90, 55 );
39 [Link]( 290, 100, 90, 55 ); Draw filled oval
40
41 } // end method paint
42
43 // execute application
44 public static void main( String args[] )
45 {
46 LinesRectsOvals application = new LinesRectsOvals();
47 [Link]( JFrame.EXIT_ON_CLOSE );
48 }
49
50 } // end class LinesRectsOvals
Altura y anchura del arco necesario para construir
RoundedRectangle
(x, y)
arc height
a rc width height
width
Medidas para construir un óvalo en base al rectángulo que lo
contiene
(x , y)
height
width
6 Pintar Arcos
Arco
− Porción de un óvalo
− Se miden en grados
− Barre (Sweeps) el número de grados que
indique el ángulo de arco
− Sweep empieza en el inicio de medida de
los ángulos
Barre en sentido contrario a las agujas del
reloj si el ángulo es positivo
Barre en sentido de las agujas del reloj para
ángulos negativos.
Ángulos positivos y negativos
Positive angles Negative angles
90° 90°
180° 0° 180° 0°
270° 270°
Métodos de la clase Graphics para el pintado de arcos
Method Description
public void drawArc( int x, int y, int width, int height, int startAngle,
int arcAngle )
Draws an arc relative to the bounding rectangle’s top-left coordinates (x, y) with
the specified width and height. The arc segment is drawn starting at
startAngle and sweeps arcAngle degrees.
public void fillArc( int x, int y, int width, int height, int startAngle,
int arcAngle )
Draws a solid arc (i.e., a sector) relative to the bounding rectangle’s top-left
coordinates (x, y) with the specified width and height. The arc segment is
drawn starting at startAngle and sweeps arcAngle degrees.
1 // Fig. 12.19: [Link]
2 // Drawing arcs. [Link]
3 import [Link].*;
4 import [Link].*; Lines 24-26
5
6 public class DrawArcs extends JFrame {
7
8 // set window's title bar String and dimensions
9 public DrawArcs()
10 {
11 super( "Drawing Arcs" );
12
13 setSize( 300, 170 );
14 setVisible( true );
15 }
16
17 // draw rectangles and arcs
18 public void paint( Graphics g )
19 {
20 [Link]( g ); // call superclass's paint method
21
22 // start at 0 and sweep 360 degrees
23 [Link]( [Link] ); Draw first arc that
24 [Link]( 15, 35, 80, 80 ); sweeps 360 degrees and
25 [Link]( [Link] ); is contained in rectangle
26 [Link]( 15, 35, 80, 80, 0, 360 );
27
28 // start at 0 and sweep 110 degrees
29 [Link]( [Link] ); Draw second arc that
30 [Link]( 100, 35, 80, 80 );
sweeps 110 degrees and
31 [Link]( [Link] );
32 [Link]( 100, 35, 80, 80, 0, 110 );
is contained in rectangle
33
34 // start at 0 and sweep -270 degrees
35 [Link]( [Link] ); Draw third arc that
36 [Link]( 185, 35, 80, 80 ); sweeps -270 degrees and
37 [Link]( [Link] );
is contained in rectangle
38 [Link]( 185, 35, 80, 80, 0, -270 );
39
40 // start at 0 and sweep 360 degrees Draw fourth arc that is filled, has starting
41 [Link]( 15, 120, 80, 40, 0, 360 ); angle 0 and sweeps 360 degrees
42
43 // start at 270 and sweep -90 degrees Draw fifth arc that is filled, has starting
44 [Link]( 100, 120, 80, 40, 270, -90 ); angle 270 and sweeps -90 degrees
45
46 // start at 0 and sweep -270 degrees
Draw sixth arc that is filled, has starting
47 [Link]( 185, 120, 80, 40, 0, -270 );
48
angle 0 and sweeps -270 degrees
49 } // end method paint
50
51 // execute application
52 public static void main( String args[] )
53 {
54 DrawArcs application = new DrawArcs();
55 [Link]( JFrame.EXIT_ON_CLOSE );
56 }
57
58 } // end class DrawArcs
7 Pintar Polígonos y Polilíneas
Clases Polygon
− Polígonos
Figuras de varios lados
− Polilíneas
Series de puntos conectados
Métodos Graphics para pintar poligonos y métodos de la
clase Polygon
Method Description
Graphics methods for drawing polygons
public void drawPolygon( int xPoints[], int yPoints[], int points )
Draws a polygon. The x-coordinate of each point is specified in the xPoints
array and the y-coordinate of each point is specified in the yPoints array. The
last argument specifies the number of points . This method draws a closed
polygon. If the last point is different from the first point, the polygon is closed
by a line that connects the last point to the first point.
public void drawPolyline( int xPoints[], int yPoints[], int points )
Draws a sequence of connected lines. The x-coordinate of each point is specified
in the xPoints array and the y-coordinate of each point is specified in the
yPoints array. The last argument specifies the number of points. If the last
point is different from the first point, the polyline is not closed.
public void drawPolygon( Polygon p )
Draws the specified polygon.
public void fillPolygon( int xPoints[], int yPoints[], int points )
Draws a solid polygon. The x-coordinate of each point is specified in the
xPoints array and the y-coordinate of each point is specified in the yPoints
array. The last argument specifies the number of points. This method draws a
closed polygon. If the last point is different from the first point, the polygon is
closed by a line that connects the last point to the first point.
public void fillPolygon( Polygon p )
Draws the specified solid polygon. The polygon is closed.
Métodos Graphics para pintar poligonos y métodos de la
clase Polygon
Method
Description
Polygon constructors and methods
public Polygon()
Constructs a new polygon object. The polygon does not contain any points.
public Polygon( int xValues[], int yValues[], int numberOfPoints )
Constructs a new polygon object. The polygon has numberOfPoints sides,
with each point consisting of an x-coordinate from xValues and a y-coordinate
from yValues .
public void addPoint( int x, int y )
Adds pairs of x- and y-coordinates to the Polygon .
1 // Fig. 12.21: [Link]
2 // Drawing polygons.
3 import [Link].*;
4 import [Link].*;
5
6 public class DrawPolygons extends JFrame {
7
8 // set window's title bar String and dimensions
9 public DrawPolygons()
10 {
11 super( "Drawing Polygons" );
12
13 setSize( 275, 230 );
14 setVisible( true );
15 }
16
17 // draw polygons and polylines
int arrays specifying
18 public void paint( Graphics g )
19 {
Polygon polygon1 points
20 [Link]( g ); // call superclass's paint method
21
Draw polygon1 to screen
22 int xValues[] = { 20, 40, 50, 30, 20, 15 };
23 int yValues[] = { 50, 50, 60, 80, 80, 60 };
24 Polygon polygon1 = new Polygon( xValues, yValues, 6 );
25
26 [Link]( polygon1 );
27
28 int xValues2[] = { 70, 90, 100, 80, 70, 65, 60 };
29 int yValues2[] = { 100, 100, 110, 110, 130, 110, 90 };
30 int arrays specifying
31 [Link]( xValues2, yValues2, 7 ); Polyline points
32
33 int xValues3[] = { 120, 140, 150, 190 }; Draw Polyline to screen
34 int yValues3[] = { 40, 70, 80, 60 };
35
36 [Link]( xValues3, yValues3, 4 ); Specify points and draw (filled)
37 Polygon to screen
38 Polygon polygon2 = new Polygon();
39 [Link]( 165, 135 );
40 [Link]( 175, 150 );
41 [Link]( 270, 200 ); Method addPoint adds pairs of
42 [Link]( 200, 220 ); x-y coordinates to a Polygon
43 [Link]( 130, 180 );
44
45 [Link]( polygon2 );
46
47 } // end method paint
48
49 // execute application
50 public static void main( String args[] )
51 {
52 DrawPolygons application = new DrawPolygons();
53 [Link]( JFrame.EXIT_ON_CLOSE );
54 }
55
56 } // end class DrawPolygons
8 Java2D API
Java 2D API
− Proporciona capacidades gráficas avanzas 2D
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
− Usa la clase [Link].Graphics2D
Extiende la clase [Link]
12.8 Java2D API
Java 2D formas
− Paquetes [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
1 // Fig. 12.22: [Link]
2 // Demonstrating some Java2D shapes.
3 import [Link].*;
4 import [Link].*; [Link]
5 import [Link].*;
6 import [Link].*;
7
8 public class Shapes extends JFrame {
9
10 // set window's title bar String and dimensions
11 public Shapes()
12 {
13 super( "Drawing 2D shapes" );
14
15 setSize( 425, 160 );
16 setVisible( true );
17 }
18
19 // draw shapes with Java2D API
20 public void paint( Graphics g )
21 {
22 [Link]( g ); // call superclass's paint method
23
24 Graphics2D g2d = ( Graphics2D ) g; // cast g to Graphics2D
25
26 // draw 2D ellipse filled with a blue-yellow gradient Use GradientPaint to
27 [Link]( new GradientPaint( 5, 30, [Link], 35, 100, fill shape with gradient
28 [Link], true ) );
29 [Link]( new [Link]( 5, 30, 65, 100 ) );
Fill ellipse with gradient
30
31 // draw 2D rectangle in red
Use BasicStroke to draw
32 [Link]( [Link] );
33 [Link]( new BasicStroke( 10.0f ) );
2D red-border rectangle
34 [Link]( new [Link]( 80, 30, 65, 100 ) );
35
36 // draw 2D rounded rectangle with a buffered background BufferedImage produces
37 BufferedImage buffImage = new BufferedImage( 10, 10, image to be manipulated
38 BufferedImage.TYPE_INT_RGB );
39
40 Graphics2D gg = [Link]();
41 [Link]( [Link] ); // draw in yellow
42 [Link]( 0, 0, 10, 10 ); // draw a filled rectangle Draw texture into
43 [Link]( [Link] ); // draw in black BufferedImage
44 [Link]( 1, 1, 6, 6 ); // draw a rectangle
45 [Link]( [Link] ); // draw in blue
46 [Link]( 1, 1, 3, 3 ); // draw a filled rectangle
47 [Link]( [Link] ); // draw in red
48 [Link]( 4, 4, 3, 3 ); // draw a filled rectangle
49
50 // paint buffImage onto the JFrame
Use BufferedImage as texture
51 [Link]( new TexturePaint( buffImage,
52 new Rectangle( 10, 10 ) ) );
for painting rounded rectangle
53 [Link]( new [Link]( 155, 30, 75, 100, 50, 50 ) );
54 Use [Link] to
55 // draw 2D pie-shaped arc in white
draw white-border
56 [Link]( [Link] );
57 [Link]( new BasicStroke( 6.0f ) );
2D pie-shaped arc
58 [Link]( new [Link]( 240, 30, 75, 100, 0, 270, [Link] ) );
59
60 // draw 2D lines in green and yellow
61 [Link]( [Link] );
Draw solid green line
62 [Link]( new [Link]( 395, 30, 320, 150 ) );
63
64 float dashes[] = { 10 };
65
66 [Link]( [Link] );
67 [Link]( new BasicStroke( 4, BasicStroke.CAP_ROUND,
Draw dashed yellow line
68 BasicStroke.JOIN_ROUND, 10, dashes, 0 ) );
that crosses solid green line
69 [Link]( new [Link]( 320, 30, 395, 150 ) );
70
71 } // end method paint
72
73 // execute application
74 public static void main( String args[] )
75 {
76 Shapes application = new Shapes(); [Link]
77 [Link]( JFrame.EXIT_ON_CLOSE );
78 }
79
80 } // end class Shapes
1 // Fig. 12.23: [Link]
2 // Demonstrating a general path.
3 import [Link].*;
4 import [Link].*;
5 import [Link].*;
6
7 public class Shapes2 extends JFrame {
8
9 // set window's title bar String, background color and dimensions
10 public Shapes2()
11 {
12 super( "Drawing 2D Shapes" );
13
14 getContentPane().setBackground( [Link] );
15 setSize( 400, 400 );
16 setVisible( true );
17 }
18
19 // draw general paths
20 public void paint( Graphics g ) x-y coordinates that comprise star
21 {
22 [Link]( g ); // call superclass's paint method
23
24 int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
25 int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
26
27 Graphics2D g2d = ( Graphics2D ) g; GeneralPath is a shape
28 GeneralPath star = new GeneralPath(); // create GeneralPath object constructed from straight
29 lines and complex curves
30 // set the initial coordinate of the General Path [Link]
31 [Link]( xPoints[ 0 ], yPoints[ 0 ] );
32
Line 28
33 // create the star--this does not draw the star
34 for ( int count = 1; count < [Link]; count++ ) Create star
35 [Link]( xPoints[ count ], yPoints[ count ] ); Lines 31-37
36
37 [Link](); // close the shape Lines 42-50
38
39 [Link]( 200, 200 ); // translate the origin to (200, 200)
40
41 // rotate around origin and draw stars in random colors
42 for ( int count = 1; count <= 20; count++ ) {
43 [Link]( [Link] / 10.0 ); // rotate coordinate system
44
45 // set random drawing color
46 [Link]( new Color( ( int ) ( [Link]() * 256 ),
47 ( int ) ( [Link]() * 256 ), Draw filled, randomly colored
48 ( int ) ( [Link]() * 256 ) ) ); star 20 times around origin
49
50 [Link]( star ); // draw filled star
51 }
[Link]