Graficos Y Java 2D
1 2 3 4 5 6 7 8 9 Introduccin Contextos y objetos grficos Colores Fuentes Pintar Lneas, Rectngulos y valos Pintar Arcos Pintar Polgonos and Polilneas Java2D API Ejemplo
1 Introduccin
Capacidades grficas de JAVA
Pintar figuras de 2D Uso y control colores Uso y control de fuentes Uso ms sofisticado de primitivas de dibujo en 2D
Uso de formar y polgonos 2D personalizados Relleno de figuras con colores, gradientes, patrones y texturas.
Java 2D API
Jerarqua 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 BasicStroke GradientPaint TexturePaint
Clases e interfaces del Java2D API que aparecen en el paquete [Link]
interface [Link] interface [Link] interface [Link]
GeneralPath Line2D RectangularShape Arc2D Ellipse2D Rectangle2D RoundRectangle2D
1 Introduccin
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.
(0, 0)
x +
X a xis
(x , y )
y +
Y a xis
2 Contextos y objetos grficos
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 mtodo paint de la lase Component emplea el objeto Graphics Se puede invocar por medio del mtodo repaint
public void paint( Graphics g )
3 Colores
Clase Color
Define los mtodos 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 public final static Color ORANGE public final static Color PINK public final static Color CYAN public final static Color MAGENTA public final static Color YELLOW public final static Color BLACK public final static Color WHITE public final static Color GRAY public final static Color LIGHT_GRAY public final static Color DARK_GRAY public final static Color RED public final static Color GREEN public final static Color BLUE
Color
RGB value
orange pink cyan magenta yellow black white gray light gray dark gray red green blue
255, 200, 0 255, 175, 175 0, 255, 255 255, 0, 255 255, 255, 0 0, 0, 0 255, 255, 255 128, 128, 128 192, 192, 192 64, 64, 64 255, 0, 0 0, 255, 0 0, 0, 255
Mtodos de la clase Color y mtodos 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 floatingpoint 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Fig. 12.5: [Link] // Demonstrating Colors. import [Link].*; import [Link].*; public class ShowColors extends JFrame { // constructor sets window's title bar string and dimensions public ShowColors() { Pinta la ventana cuando super( "Using colors" ); setSize( 400, 130 ); setVisible( true ); }
comienza la ejecucin de la aplicacin
// draw rectangles and Strings in different colors public void paint( Graphics g ) { // call superclass's paint method El mtodo fillRect crea un [Link]( g ); rectngulo relleno en el color de // set new drawing color using integers [Link]( new Color( 255, 0, 0 ) ); [Link]( 25, 25, 100, 20 ); [Link]( "Current RGB: " + [Link](), 130, 40 );
El mtodo setColor establece el color de pintura en base a un color RGB
pintura actual.
El mtodo drawString escribe un String en el color actual en las coordenadas especificadas
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
// set new drawing color using floats [Link]( new Color( 0.0f, 1.0f, 0.0f ) ); [Link]( 25, 50, 100, 20 ); [Link]( "Current RGB: " + [Link](), 130, 65 ); // set new drawing color using static Color objects [Link]( [Link] ); [Link]( 25, 75, 100, 20 ); [Link]( "Current RGB: " + [Link](), 130, 90 ); // display individual RGB values Color color = [Link]; [Link]( color ); [Link]( 25, 100, 100, 20 ); [Link]( "RGB values: " + [Link]() + ", " + [Link]() + ", " + [Link](), 130, 115 ); } // end method paint // execute application public static void main( String args[] ) { ShowColors application = new ShowColors(); [Link]( JFrame.EXIT_ON_CLOSE ); } } // end class ShowColors
Empleamos las constantes de la clase Color
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// Fig. 12.6: [Link] // Choosing colors with JColorChooser. import [Link].*; import [Link].*; import [Link].*; public class ShowColors2 extends JFrame { private JButton changeColorButton; private Color color = Color.LIGHT_GRAY; private Container container; // set up GUI public ShowColors2() { super( "Using JColorChooser" ); container = getContentPane(); [Link]( new FlowLayout() ); // set up changeColorButton and register its event handler changeColorButton = new JButton( "Change Color" ); [Link](
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
new ActionListener() {
// anonymous inner class
// display JColorChooser when user clicks button JColorChooser presenta public void actionPerformed( ActionEvent event ) un dilogo para { seleccionar colores color = [Link]( [Link], "Choose a color", color ); // set default color, if no color is returned if ( color == null ) color = Color.LIGHT_GRAY; // change content pane's background color [Link]( color ); } } // end anonymous inner class ); // end call to addActionListener [Link]( changeColorButton ); setSize( 400, 130 ); setVisible( true ); } // end ShowColor2 constructor
static showDialog
muestra el cuadro de dilogo
51 52 53 54 55 56 57 58
// execute application public static void main( String args[] ) { ShowColors2 application = new ShowColors2(); [Link]( JFrame.EXIT_ON_CLOSE ); } } // end class ShowColors2
[Link]
Fig. 12.7 HSB and RGB tabs of the JColorChooser dialog
4 Fuente
Clase Font
Contiene mtodos 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
Mtodos y constantes relacionados con la clase Font
Method or constant Description Font constants, constructors and methods for drawing polygons public final static int public final static int public final static int public Font( String name, public int public int getStyle() PLAIN BOLD ITALIC int style, int size )
A constant representing a plain font style. A constant representing a bold font style. A constant representing an italic font style. Creates a Font object with the specified font, style and size. Returns an integer value indicating the current font style.
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 fonts family name as a string.
public boolean public boolean public boolean isPlain()
Tests a font for a plain font style. Returns
isBold()
true if the font is plain. true if the font is bold. true if the font is italic.
Tests a font for a bold font style. Returns
isItalic()
Tests a font for an italic font style. Returns
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 object reference f.
Font
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Fig. 12.9: [Link] // Using fonts. import [Link].*; import [Link].*; public class Fonts extends JFrame { // set window's title bar and dimensions public Fonts() { super( "Using fonts" ); setSize( 420, 125 ); setVisible( true ); } // display Strings in different fonts and colors public void paint( Graphics g ) El mtodo setFont { // call superclass's paint method [Link]( g );
establece la fuente a usar
// set font to Serif (Times), bold, 12pt and draw a string [Link]( new Font( "Serif", [Link], 12 ) ); [Link]( "Serif 12 point bold.", 20, 50 ); Escribe
el texto con la configuracin actual de fuente
26 27 string 28 29 30 31 string 32 33 34 35 string 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
// set font to Monospaced (Courier), italic, 24pt and draw a [Link]( new Font( "Monospaced", [Link], 24 ) ); [Link]( "Monospaced 24 point italic.", 20, 70 ); // set font to SansSerif (Helvetica), plain, 14pt and draw a [Link]( new Font( "SansSerif", [Link], 14 ) ); [Link]( "SansSerif 14 point plain.", 20, 90 ); // set font to Serif (Times), bold/italic, 18pt and draw a [Link]( [Link] ); [Link]( new Font( "Serif", [Link] + [Link], 18 ) ); [Link]( [Link]().getName() + " " + [Link]().getSize() + " point bold italic.", 20, 110 ); } // end method paint // execute application public static void main( String args[] ) { Fonts application = new Fonts(); [Link]( JFrame.EXIT_ON_CLOSE ); } } // end class Fonts
Control de fuentes
Parmetros de medida y posicin 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
he ight
Xy1
le ading 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 Fonts 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.
// Fig. 12.12: [Link] 2 // FontMetrics and Graphics [Link] methods useful for obtaining font Line 22 Line 23 metrics. 3 import [Link].*; 4 import [Link].*; 5 Set font to SansSerif 12-point bold 6 public class Metrics extends Obtain FontMetrics JFrame { object for current font 7 8 // set window's title bar String and dimensions 9 public Metrics()
25
[Link]( "Ascent: " + [Link](), 10, 55 ); Repeat same process for 26 [Link]( "Descent:Serif 14-point italic font " Lines 25-28 + [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 );
Use FontMetrics to obtain ascent, descent, height and leading [Link]
[Link]
5 Pintar Lneas, Rectngulos y valos
Clase Graphics
Provee mtodos para pintar lneas, rectngulos y valos
Todos lo mtodos de pintar estas figuras requieren el ancho y alto que ocuparan Existen los mtodos para pintar figuras con o sin rellene (draw* y fill*)
Mtodos de la clase Graphics para pintar lneas, rectngulos 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).
Mtodos de la clase Graphics para pintar lneas, rectngulos 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 rectangles 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 rectangles 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Fig. 12.14: [Link] // Drawing lines, rectangles and ovals. import [Link].*; import [Link].*; public class LinesRectsOvals extends JFrame { // set window's title bar String and dimensions public LinesRectsOvals() { super( "Drawing lines, rectangles and ovals" ); setSize( 400, 165 ); setVisible( true ); } // display various lines, rectangles and ovals public void paint( Graphics g ) { [Link]( g ); // call superclass's paint method [Link]( [Link] ); [Link]( 5, 30, 350, 30 ); [Link]( [Link] ); [Link]( 5, 40, 90, 55 ); [Link]( 100, 40, 90, 55 );
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
[Link]( [Link] ); [Link]( 195, 40, 90, 55, 50, 50 ); [Link]( 290, 40, 90, 55, 20, 20 ); [Link]( [Link] ); g.draw3DRect( 5, 100, 90, 55, true ); g.fill3DRect( 100, 100, 90, 55, false ); [Link]( [Link] ); [Link]( 195, 100, 90, 55 ); [Link]( 290, 100, 90, 55 ); } // end method paint
Draw filled rounded rectangle
Draw (non-filled) rounded rectangle Draw 3D rectangle Draw filled 3D rectangle Draw oval Draw filled oval
// execute application public static void main( String args[] ) { LinesRectsOvals application = new LinesRectsOvals(); [Link]( JFrame.EXIT_ON_CLOSE ); } } // 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 rectngulo que lo contiene
(x , y)
height
width
6 Pintar Arcos
Arco
Porcin de un valo Se miden en grados Barre (Sweeps) el nmero 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 90
Negative angles 90
180
180
270
270
Mtodos 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 rectangles 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 rectangles top-left coordinates (x, y) with the specified width and height. The arc segment is drawn starting at startAngle and sweeps arcAngle degrees.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// Fig. 12.19: [Link] // Drawing arcs. import [Link].*; import [Link].*; public class DrawArcs extends JFrame { // set window's title bar String and dimensions public DrawArcs() { super( "Drawing Arcs" ); setSize( 300, 170 ); setVisible( true ); } // draw rectangles and arcs public void paint( Graphics g ) { [Link]( g ); // call superclass's paint method // start at 0 and sweep 360 degrees [Link]( [Link] ); [Link]( 15, 35, 80, 80 ); [Link]( [Link] ); [Link]( 15, 35, 80, 80, 0, 360 );
[Link] Lines 24-26
Draw first arc that sweeps 360 degrees and is contained in rectangle
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
// start at 0 and sweep 110 degrees [Link]( [Link] ); [Link]( 100, 35, 80, 80 ); [Link]( [Link] ); [Link]( 100, 35, 80, 80, 0, 110 ); // start at 0 and sweep -270 degrees [Link]( [Link] ); [Link]( 185, 35, 80, 80 ); [Link]( [Link] ); [Link]( 185, 35, 80, 80, 0, -270 ); // start at 0 and sweep 360 degrees [Link]( 15, 120, 80, 40, 0, 360 ); // start at 270 and sweep -90 degrees [Link]( 100, 120, 80, 40, 270, -90 ); // start at 0 and sweep -270 degrees [Link]( 185, 120, 80, 40, 0, -270 ); } // end method paint
Draw second arc that sweeps 110 degrees and is contained in rectangle
Draw third arc that sweeps -270 degrees and is contained in rectangle Draw fourth arc that is filled, has starting angle 0 and sweeps 360 degrees Draw fifth arc that is filled, has starting angle 270 and sweeps -90 degrees Draw sixth arc that is filled, has starting angle 0 and sweeps -270 degrees
51 52 53 54 55 56 57 58
// execute application public static void main( String args[] ) { DrawArcs application = new DrawArcs(); [Link]( JFrame.EXIT_ON_CLOSE ); } } // end class DrawArcs
7 Pintar Polgonos y Polilneas
Clases Polygon
Polgonos
Figuras de varios lados Series de puntos conectados
Polilneas
Mtodos Graphics para pintar poligonos y mtodos 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.
Mtodos Graphics para pintar poligonos y mtodos de la clase Polygon
Method Description
Polygon constructors and methods
public public Polygon()
Constructs a new polygon object. The polygon does not contain any points.
Polygon( int xValues[], int yValues[], int numberOfPoints ) numberOfPoints sides, xValues and a y-coordinate
Constructs a new polygon object. The polygon has with each point consisting of an x-coordinate from from yValues .
public void addPoint( int x, int y )
Adds pairs of x- and y-coordinates to the
Polygon .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Fig. 12.21: [Link] // Drawing polygons. import [Link].*; import [Link].*; public class DrawPolygons extends JFrame { // set window's title bar String and dimensions public DrawPolygons() { super( "Drawing Polygons" ); setSize( 275, 230 ); setVisible( true ); } // draw polygons and polylines public void paint( Graphics g ) { [Link]( g ); // call superclass's paint method int xValues[] = { 20, 40, 50, 30, 20, 15 }; int yValues[] = { 50, 50, 60, 80, 80, 60 }; Polygon polygon1 = new Polygon( xValues, yValues, 6 ); [Link]( polygon1 );
int arrays specifying Polygon polygon1 points Draw polygon1 to screen
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
int xValues2[] = { 70, 90, 100, 80, 70, 65, 60 }; int yValues2[] = { 100, 100, 110, 110, 130, 110, 90 }; [Link]( xValues2, yValues2, 7 ); int xValues3[] = { 120, 140, 150, 190 }; int yValues3[] = { 40, 70, 80, 60 }; [Link]( xValues3, yValues3, 4 ); Polygon polygon2 = new Polygon(); [Link]( 165, 135 ); [Link]( 175, 150 ); [Link]( 270, 200 ); [Link]( 200, 220 ); [Link]( 130, 180 ); [Link]( polygon2 ); } // end method paint // execute application public static void main( String args[] ) { DrawPolygons application = new DrawPolygons(); [Link]( JFrame.EXIT_ON_CLOSE ); } } // end class DrawPolygons
int arrays specifying Polyline points Draw Polyline to screen Specify points and draw (filled) Polygon to screen
Method addPoint adds pairs of x-y coordinates to a Polygon
8 Java2D API
Java 2D API
Proporciona capacidades grficas 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// Fig. 12.22: [Link] // Demonstrating some Java2D shapes. import [Link].*; import [Link].*; import [Link].*; import [Link].*; public class Shapes extends JFrame { // set window's title bar String and dimensions public Shapes() { super( "Drawing 2D shapes" ); setSize( 425, 160 ); setVisible( true ); } // draw shapes with Java2D API public void paint( Graphics g ) { [Link]( g ); // call superclass's paint method Graphics2D g2d = ( Graphics2D ) g; // cast g to Graphics2D
[Link]
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
// draw 2D ellipse filled with a blue-yellow gradient [Link]( new GradientPaint( 5, 30, [Link], 35, 100, [Link], true ) ); [Link]( new [Link]( 5, 30, 65, 100 ) ); // draw 2D rectangle in red [Link]( [Link] ); [Link]( new BasicStroke( 10.0f ) ); [Link]( new [Link]( 80, 30, 65, 100 ) ); // draw 2D rounded rectangle with a buffered background BufferedImage buffImage = new BufferedImage( 10, 10, BufferedImage.TYPE_INT_RGB ); Graphics2D gg = [Link](); [Link]( [Link] ); // draw in yellow [Link]( 0, 0, 10, 10 ); // draw a filled rectangle [Link]( [Link] ); // draw in black [Link]( 1, 1, 6, 6 ); // draw a rectangle [Link]( [Link] ); // draw in blue [Link]( 1, 1, 3, 3 ); // draw a filled rectangle [Link]( [Link] ); // draw in red [Link]( 4, 4, 3, 3 ); // draw a filled rectangle
Use GradientPaint to fill shape with gradient Fill ellipse with gradient Use BasicStroke to draw 2D red-border rectangle
BufferedImage produces image to be manipulated
Draw texture into BufferedImage
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
// paint buffImage onto the JFrame [Link]( new TexturePaint( buffImage, new Rectangle( 10, 10 ) ) ); [Link]( new [Link]( 155, 30, 75, 100, 50, 50 ) ); // draw 2D pie-shaped arc in white [Link]( [Link] ); [Link]( new BasicStroke( 6.0f ) ); [Link]( new [Link]( 240, 30, 75, 100, 0, 270, [Link] ) ); // draw 2D lines in green and yellow [Link]( [Link] ); [Link]( new [Link]( 395, 30, 320, 150 ) ); float dashes[] = { 10 }; [Link]( [Link] ); [Link]( new BasicStroke( 4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10, dashes, 0 ) ); [Link]( new [Link]( 320, 30, 395, 150 ) ); } // end method paint
Use BufferedImage as texture for painting rounded rectangle Use [Link] to draw white-border 2D pie-shaped arc
Draw solid green line
Draw dashed yellow line that crosses solid green line
73 74 75 76 77 78 79 80
// execute application public static void main( String args[] ) { Shapes application = new Shapes(); [Link]( JFrame.EXIT_ON_CLOSE ); } } // end class Shapes
[Link]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// Fig. 12.23: [Link] // Demonstrating a general path. import [Link].*; import [Link].*; import [Link].*; public class Shapes2 extends JFrame { // set window's title bar String, background color and dimensions public Shapes2() { super( "Drawing 2D Shapes" ); getContentPane().setBackground( [Link] ); setSize( 400, 400 ); setVisible( true ); } // draw general paths public void paint( Graphics g ) { [Link]( g ); // call superclass's paint method int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 }; int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
x-y coordinates that comprise star
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
Graphics2D g2d = ( Graphics2D ) g; GeneralPath star = new GeneralPath(); // create GeneralPath object // set the initial coordinate of the General Path [Link]( xPoints[ 0 ], yPoints[ 0 ] ); // create the star--this does not draw the star for ( int count = 1; count < [Link]; count++ ) [Link]( xPoints[ count ], yPoints[ count ] ); [Link](); // close the shape [Link]( 200, 200 ); // translate the origin to (200, 200) // rotate around origin and draw stars in random colors for ( int count = 1; count <= 20; count++ ) { [Link]( [Link] / 10.0 ); // rotate coordinate system // set random drawing color [Link]( new Color( ( int ) ( [Link]() * 256 ), ( int ) ( [Link]() * 256 ), ( int ) ( [Link]() * 256 ) ) ); [Link]( star ); // draw filled star }
GeneralPath is a shape constructed from straight lines and complex curves [Link] Line 28 Create star Lines 31-37 Lines 42-50
Draw filled, randomly colored star 20 times around origin
[Link]