Chapter 11 - Graphics and Java 2D Outline

Chapter 11 - Graphics and Java 2D Outline 11.1 Introduction 11.2 Graphics Contexts and Graphics Objects 11.3 Color Control 11.4 Font Control 11.5 Drawing Lines, Rectangles and Ovals 11.6 Drawing Arcs 11.7 Drawing Polygons and Polylines 11.8 The Java 2D API 11.9 Java 2D Shapes 11.10 (Optional Case Study) Thinking About Objects: Designing Interfaces with the UML 11.1 Introduction Javas graphics capabilities Drawing 2D shapes Controlling colors Controlling fonts Java 2D API More sophisticated graphics capabilities Drawing custom 2D shapes Filling shapes with colors and patterns Fig 11.1 Some classes and interfaces used in this chapter from Javas original graphics capabilities and from the Java2D API java.lang.Object Key java.awt.Color class

java.awt.Component interface java.awt.Font java.awt.FontMetrics java.awt.Graphics java.awt.Polygon Classes and interfa ces from the J ava2D API java.awt.Graphics2D java.awt.Paint java.awt.BasicStroke java.awt.Shape java.awt.GradientPaint java.awt.Stroke java.awt.TexturePaint java.awt.geom.GeneralPath java.awt.geom.Line2D java.awt.geom.RectangularShape java.awt.geom.Arc2D java.awt.geom.Ellipse2D java.awt.geom.Rectangle2D java.awt.geom.RoundRectangle2D Fig. 11.2 Java coordinate system. Units are measured in pixels. +x (0, 0) (x, y) +y Y a xis X a xis 11.2 Graphics Context and Graphics Objects

Graphics context Enables drawing on screen Graphics object manages graphics context Controls how information is drawn Class Graphics is abstract Cannot be instantiated Contributes to Javas portability Class Component method paint takes Graphics object public void paint( Graphics g ) Called through method repaint Class Color Defines methods and constants for manipulating colors Colors are created from red, green and blue components RGB values Fig. 11.3 Color class static constants and RGB values. 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 lightGray light gray 192, 192, 192 public final static Color darkGray 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 Fig. 11.3 Color class static constants and RGB values Fig. 11.4 Color methods and colorrelated Graphics methods. Method Description public Color( int r, int g, Creates a color based on red, green and blue contents int b ) expressed as integers from 0 to 255. public Color( float r, float g, float b ) Creates a color based on red, green and blue contents expressed as floating-point values from 0.0 to 1.0. public int getRed() // Color class Returns a value between 0 and 255 representing the red content. public int getGreen() // Color class Returns a value between 0 and 255 representing the green content. public int getBlue() // Color class Returns a value between 0 and 255 representing the blue content.

public Color getColor() // Graphics class Returns a Color object representing the current color for the graphics context. public void setColor( Color Sets the current color for drawing with the graphics context. c ) // Graphics class Fig. 11.4 Color methods and c olor-related Graphics methods. 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 28 29 30 31 32 33 34 35

Outline // Fig. 11.5: ShowColors.java // Demonstrating Colors. // Java core packages import java.awt.*; import java.awt.event.*; ShowColors.java Line 23 // Java extension packages import javax.swing.*; Line 29 public class ShowColors extends JFrame { // constructor sets window's title bar string and dimensions public ShowColors() { Paint window when super( "Using colors" ); setSize( 400, 130 ); setVisible( true ); Line 30 Line 31 application begins execution } // draw rectangles and Strings in different colors public void paint( Graphics g ) { // call superclass's paint method super.paint( g ); Method setColor sets colors RGB value Method fillRect creates filled rectangle at specified coordinates using current RGB value // set new drawing color using integers g.setColor( new Color( 255, 0, 0 ) );

g.fillRect( 25, 25, 100, 20 ); g.drawString( "Current RGB: " + g.getColor(), 130, 40 ); // set new drawing color using floats g.setColor( new Color( 0.0f, 1.0f, 0.0f ) ); g.fillRect( 25, 50, 100, 20 ); 2002 Prentice Hall, Inc. All rights reserved. Method drawString draw colored text at specified coordinates 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 g.drawString( "Current RGB: " + g.getColor(), 130, 65 ); // set new drawing color using static Color objects g.setColor( Color.blue ); g.fillRect( 25, 75, 100, 20 ); g.drawString( "Current RGB: " + g.getColor(), 130, 90 ); // display individual RGB values Color color = Color.magenta; g.setColor( color ); g.fillRect( 25, 100, 100, 20 ); g.drawString( "RGB values: " + color.getRed() + ", " +

color.getGreen() + ", " + color.getBlue(), 130, 115 ); } // execute application public static void main( String args[] ) { ShowColors application = new ShowColors(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class ShowColors 2002 Prentice Hall, Inc. All rights reserved. Outline ShowColors.java Lines 39 and 44 Use constant in class Color to specify current color 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 28 29 30 31 32 33 34 35 Outline // Fig. 11.6: ShowColors2.java // Demonstrating JColorChooser. // Java core packages import java.awt.*; import java.awt.event.*; ShowColors2.java // Java extension packages import javax.swing.*; Line 35 public class ShowColors2 extends JFrame { private JButton changeColorButton; private Color color = Color.lightGray; private Container container; Line 35 // set up GUI public ShowColors2() { super( "Using JColorChooser" ); container = getContentPane(); container.setLayout( new FlowLayout() ); JColorChooser allows user to choose from among several colors // set up changeColorButton and register its event handler changeColorButton = new JButton( "Change Color" ); changeColorButton.addActionListener( // anonymous inner class

new ActionListener() { // display JColorChooser when user clicks button public void actionPerformed( ActionEvent event ) { color = JColorChooser.showDialog( 2002 Prentice Hall, Inc. All rights reserved. static method showDialog displays the color chooser dialog 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 ShowColors2.this, "Choose a color", color ); // set default color, if no color is returned if ( color == null ) color = Color.lightGray;

// change content pane's background color container.setBackground( color ); } } // end anonymous inner class ); // end call to addActionListener container.add( changeColorButton ); setSize( 400, 130 ); setVisible( true ); } // execute application public static void main( String args[] ) { ShowColors2 application = new ShowColors2(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class ShowColors2 2002 Prentice Hall, Inc. All rights reserved. Outline ShowColors2.java Outline ShowColors2.java 2002 Prentice Hall, Inc. All rights reserved. Fig. 11.7 The HSB and RGB of the JColorChooser dialog 11.4 Font Control Class Font Contains methods and constants for font control Font constructor takes three arguments Font name: Monospaced, SansSerif, Serif, etc. Font style: Font.PLAIN, Font.ITALIC and Font.BOLD Font size: Measured in points (1/72 of inch) Method or constant

public final static int PLAIN // Font class public final static int BOLD // Font class Description A constant representing a plain font style. A constant representing a bold font style. public final static int ITALIC A constant representing an italic font style. // Font class public Font( String name, int style, int size ) public int getStyle() // Font class Creates a Font object with the specified font, style and size. public int getSize() // Font class public String getName() // Font class public String getFamily() // Font class Returns an integer value indicating the current font size. Returns an integer value indicating the current font style. Returns the current font name as a string. Returns the fonts family name as a string. Fig. 11.8 Font methods, constants and font-related Graphics methods (Part 1 of 2). Font methods, constants and related Graphics methods Method or constant public boolean isPlain() // Font class Description public boolean isBold() // Font class Tests a font for a bold font style. Returns true if the font is bold.

public boolean isItalic() // Font class Tests a font for an italic font style. Returns true if the font is italic. public Font getFont() // Graphics class Returns a Font object reference representing the current font. Tests a font for a plain font style. Returns true if the font is plain. public void setFont( Font f ) Sets the current font to the font, style and size specified // Graphics class by the Font object reference f. Fig. 11.8 Font methods, constants and font-related Graphics methods (Part 2 of 2). 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 28 29 30 31 32 33 34 35 Outline // Fig. 11.9: Fonts.java // Using fonts // Java core packages import java.awt.*; import java.awt.event.*; Fonts.java Line 30 // Java extension packages import javax.swing.*; Line 31 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 ) { // call superclass's paint method super.paint( g ); Method setFont sets current font // set current font to Serif (Times), bold, 12pt // and draw a string g.setFont( new Font( "Serif", Font.BOLD, 12 ) ); g.drawString( "Serif 12 point bold.", 20, 50 );

// set current font to Monospaced (Courier), // italic, 24pt and draw a string g.setFont( new Font( "Monospaced", Font.ITALIC, 24 ) ); 2002 Prentice Hall, Inc. All rights reserved. Draw text using current font 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 g.drawString( "Monospaced 24 point italic.", 20, 70 ); // set current font to SansSerif (Helvetica), // plain, 14pt and draw a string g.setFont( new Font( "SansSerif", Font.PLAIN, 14 ) ); g.drawString( "SansSerif 14 point plain.", 20, 90 ); // set current font to Serif (times), bold/italic, // 18pt and draw a string g.setColor( Color.red ); Set font g.setFont( new Font( "Serif", Font.BOLD + Font.ITALIC, 18 ) ); g.drawString( g.getFont().getName() + " " +

g.getFont().getSize() + " point bold italic.", 20, 110 ); Fonts.java Line 41 to SansSerif 14-point plain Lines 46-47 Set font to Serif 18-point bold italic } // execute application public static void main( String args[] ) { Fonts application = new Fonts(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } Outline // end class Fonts 2002 Prentice Hall, Inc. All rights reserved. 11.4 Font metrics Font Control (cont.) Height Descent (amount character dips below baseline) Ascent (amount character rises above baseline) Leading (difference between descent and ascent) height Xy1

leading ascent baseline descent Fig. 11.11 FontMetrics and Graphics methods for obtaining font metrics. Method public int getAscent() // FontMetrics class public int getDescent() // FontMetrics class Description Returns a value representing the ascent of a font in points. Returns a value representing the descent of a font in points. public int getLeading() // FontMetrics class Returns a value representing the leading of a font in points. public int getHeight() // FontMetrics class Returns a value representing the height of a font in points. public FontMetrics getFontMetrics() // Graphics class Returns the FontMetrics object for the current drawing Font. public FontMetrics Returns the FontMetrics object for the specified Font argument. getFontMetrics( Font f ) // Graphics class Fig. 11.11 FontMetrics and Graphics methods for obtaining font metrics. 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 28 29 30 31 32 33 34 35 Outline // Fig. 11.12: Metrics.java // Demonstrating methods of class FontMetrics and // class Graphics useful for obtaining font metrics. Metrics.java // Java core packages import java.awt.*; import java.awt.event.*; Line 29 // Java extension packages import javax.swing.*;

Line 30 public class Metrics extends JFrame { Lines 32-35 // set window's title bar String and dimensions public Metrics() { super( "Demonstrating FontMetrics" ); setSize( 510, 210 ); setVisible( true ); } // display font metrics public void paint( Graphics g ) { // call superclass's paint method super.paint( g ); Set font to SansSerif 12-point bold g.setFont( new Font( "SansSerif", Font.BOLD, 12 ) ); FontMetrics metrics = g.getFontMetrics(); g.drawString( "Current font: " + g.getFont(), 10, 40 ); g.drawString( "Ascent: " + metrics.getAscent(), 10, 55 ); g.drawString( "Descent: " + metrics.getDescent(), 10, 70 ); g.drawString( "Height: " + metrics.getHeight(), 10, 85 ); g.drawString( "Leading: " + metrics.getLeading(), 10, 100); 2002 Prentice Hall, Inc. All rights reserved. Obtain FontMetrics object for current font Use FontMetrics to obtain ascent, descent, height and leading 36 37 38 39 40 41 42 43 44 45 46

47 48 49 50 51 52 53 54 55 56 Outline Font font = new Font( "Serif", Font.ITALIC, 14 ); Repeat same process for metrics = g.getFontMetrics( font ); Serif 14-point italic font g.setFont( font ); Metrics.java g.drawString( "Current font: " + font, 10, 130 ); g.drawString( "Ascent: " + metrics.getAscent(), 10, 145 ); g.drawString( "Descent: " + metrics.getDescent(), 10, 160); Lines 37-44 g.drawString( "Height: " + metrics.getHeight(), 10, 175 ); g.drawString( "Leading: " + metrics.getLeading(), 10, 190); } // execute application public static void main( String args[] ) { Metrics application = new Metrics(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class Metrics 2002 Prentice Hall, Inc. All rights reserved. 11.5 Drawing Lines, Rectangles and Ovals Class Graphics Provides methods for drawing lines, rectangles and ovals All drawing methods require parameters width and height Method

Description public void drawLine( int x1, Draws a line between the point (x1, y1) and the point (x2, y2). int y1, int x2, int y2 ) public void drawRect( int x, Draws a rectangle of the specified width and height. The topint y, int width, int height ) left corner of the rectangle has the coordinates (x, y). public void fillRect( int x, Draws a solid rectangle with the specified width and height. int y, int width, int height ) The top-left corner of the rectangle has the coordinate (x, y). public void clearRect( int x, Draws a solid rectangle with the specified width and height in int y, int width, int height ) the current background color. The top-left corner of the rectangle has the coordinate (x, y). public void drawRoundRect( int Draws a rectangle with rounded corners in the current color with the x, int y, int width, int specified width and height. The arcWidth and arcHeight height, int arcWidth, int determine the rounding of the corners (see Fig. 11.15). arcHeight ) public void fillRoundRect( int Draws a solid rectangle with rounded corners in the current color x, int y, int width, int with the specified width and height. The arcWidth and height, int arcWidth, int arcHeight determine the rounding of the corners (see Fig. 11.15). arcHeight ) Fig. 11.13 Graphics methods that draw lines, rectangles and ovals (Part 1 of 2). Fig. 11.13 Graphics methods that draw lines, rectangle and ovals (Part 2). Method Description 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 is 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. 11.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. 11.16). Fig. 11.13 Graphics methods that draw lines, rectangles and ovals (Part 2 o f 2). 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 28 29 30

31 32 33 34 35 // Fig. 11.14: LinesRectsOvals.java // Drawing lines, rectangles and ovals // Java core packages import java.awt.*; import java.awt.event.*; // Java extension packages import javax.swing.*; 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 ) { // call superclass's paint method super.paint( g ); g.setColor( Color.red ); g.drawLine( 5, 30, 350, 30 ); g.setColor( Color.blue ); g.drawRect( 5, 40, 90, 55 ); g.fillRect( 100, 40, 90, 55 ); g.setColor( Color.cyan ); 2002 Prentice Hall, Inc. All rights reserved. Outline LinesRectsOvals. java 36 37 38 39 40 41 42 43

44 45 46 47 48 49 50 51 52 53 54 55 56 57 g.fillRoundRect( 195, 40, 90, 55, 50, 50 ); g.drawRoundRect( 290, 40, 90, 55, 20, 20 ); g.setColor( Color.yellow ); g.draw3DRect( 5, 100, 90, 55, true ); g.fill3DRect( 100, 100, 90, 55, false ); g.setColor( Color.magenta ); g.drawOval( 195, 100, 90, 55 ); g.fillOval( 290, 100, 90, 55 ); Draw filled rounded rectangle Outline Draw (non-filled) rounded rectangle Draw 3D rectangleLinesRectsOvals. java Draw filled 3D rectangle Line 36 Draw oval Line 37 Draw filled oval } // execute application public static void main( String args[] ) { LinesRectsOvals application = new LinesRectsOvals(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class LinesRectsOvals

2002 Prentice Hall, Inc. All rights reserved. Line 40 Line 41 Line 44 Line 45 Fig. 11.15 The arc width and height for rounded rectangles. (x, y) arc height a rc width height width Fig. 11.16 An oval bounded by a rectangle. (x, y) height wid th Fig. 11.17 Arc Positive and negative arc angles. Portion of oval Measured in degrees Sweeps the number of degrees in arc angle Sweep starts at starting angle Counterclockwise sweep is measure in positive degrees Clockwise sweep is measure in negative degrees Negative angles 90 Positive angles 90

180 0 270 180 0 270 11.18 Graphics methods for drawing arcs. 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, Draws a solid arc (i.e., a sector) relative to the bounding int y, int width, int height, rectangles top-left coordinates (x, y) with the specified int startAngle, int arcAngle ) width and height. The arc segment is drawn starting at startAngle and sweeps arcAngle degrees. Fig. 11.18 Graphics methods for drawing arc s. 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 28 29 30 31 32 33 34 35 // Fig. 11.19: DrawArcs.java // Drawing arcs // Java core packages import java.awt.*; import java.awt.event.*; // Java extension packages import javax.swing.*; Outline DrawArcs.java Lines 29-32 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 ) { // call superclass's paint method super.paint( g ); // start at 0 and sweep 360 degrees g.setColor( Color.yellow ); g.drawRect( 15, 35, 80, 80 ); g.setColor( Color.black ); g.drawArc( 15, 35, 80, 80, 0, 360 ); // start at 0 and sweep 110 degrees g.setColor( Color.yellow ); 2002 Prentice Hall, Inc. All rights reserved. Draw first arc that sweeps 360 degrees and is contained in rectangle 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

63 64 65 g.drawRect( 100, 35, 80, 80 ); g.setColor( Color.black ); g.drawArc( 100, 35, 80, 80, 0, 110 ); // start at 0 and sweep -270 degrees g.setColor( Color.yellow ); g.drawRect( 185, 35, 80, 80 ); g.setColor( Color.black ); g.drawArc( 185, 35, 80, 80, 0, -270 ); // start at 0 and sweep 360 degrees g.fillArc( 15, 120, 80, 40, 0, 360 ); // start at 270 and sweep -90 degrees g.fillArc( 100, 120, 80, 40, 270, -90 ); // start at 0 and sweep -270 degrees g.fillArc( 185, 120, 80, 40, 0, -270 ); } // execute application public static void main( String args[] ) { DrawArcs application = new DrawArcs(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class DrawArcs 2002 Prentice Hall, Inc. All rights reserved. Draw second arc that Outline sweeps 110 degrees and is contained in rectangle DrawArcs.java Draw third arc that Lines 35-38 sweeps -270 degrees and is contained in rectangle Lines 41-44 Draw fourth arc that is filled, has starting Line360 47 degrees angle 0 and sweeps 50 has starting

Draw fifth arc thatLine is filled, angle 270 and sweeps -90 degrees Line 53 Draw sixth arc that is filled, has starting angle 0 and sweeps -270 degrees Outline DrawArcs.java. Output 2002 Prentice Hall, Inc. All rights reserved. 11.7 Drawing Polygons and Polylines Class Polygon Polygons: Multisided shapes Polylines: Series of connected points Method Description public void drawPolygon( int xPoints[], Draws a polygon. The x-coordinate of each point is specified in the xPoints int yPoints[],int points ) 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 polygoneven if the last point is different from the first point. public void drawPolyline( Draws a series of connected lines. The x-coordinate of each point is specified in int xPoints[], int yPoints[], the xPoints array and the y-coordinate of each point is specified in the int points ) 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 closed polygon. public void fillPolygon( int xPoints[], Draws a solid polygon. The x-coordinate of each point is specified in the int yPoints[], int points ) 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 polygoneven if the last point is different from the first point. public void fillPolygon( Polygon p ) Draws the specified solid polygon. The polygon is closed. public Polygon() Constructs a new polygon object. The polygon does not contain any points. // Polygon class public Polygon( int xValues[], Constructs a new polygon object. The polygon has numberOfPoints sides, int yValues[], int numberOfPoints ) with each point consisting of an x-coordinate from xValues and a y-coordinate

// Polygon class from yValues. Fig. 11.20 Graphics methods for drawing polygons and class Polygon constructors. 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 28 29 30 31 32 33 34 35 // Fig. 11.21: DrawPolygons.java // Drawing polygons // Java core packages import java.awt.*; import java.awt.event.*; // Java extension packages import javax.swing.*;

Outline DrawPolygons.java Lines 28-29 Line 32 public class DrawPolygons extends JFrame { // set window's title bar String and dimensions public DrawPolygons() { super( "Drawing Polygons" ); Lines 34-35 setSize( 275, 230 ); setVisible( true ); } // draw polygons and polylines public void paint( Graphics g ) { // call superclass's paint method super.paint( g ); int xValues[] = { 20, 40, 50, 30, 20, 15 }; int yValues[] = { 50, 50, 60, 80, 80, 60 }; Polygon polygon1 = new Polygon( xValues, yValues, 6 ); g.drawPolygon( polygon1 ); int xValues2[] = { 70, 90, 100, 80, 70, 65, 60 }; int yValues2[] = { 100, 100, 110, 110, 130, 110, 90 }; 2002 Prentice Hall, Inc. All rights reserved. int arrays specifying Polygon polygon1 points Draw polygon1 to screen int arrays specifying Polygon polygon2 points 36 37 38 39 40 41 42 43 44

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 g.drawPolyline( xValues2, yValues2, 7 ); int xValues3[] = { 120, 140, 150, 190 }; int yValues3[] = { 40, 70, 80, 60 }; g.fillPolygon( xValues3, yValues3, 4 ); Polygon polygon2 = polygon2.addPoint( polygon2.addPoint( polygon2.addPoint( polygon2.addPoint( polygon2.addPoint( new Polygon(); 165, 135 ); 175, 150 ); 270, 200 ); 200, 220 ); 130, 180 ); g.fillPolygon( polygon2 ); } // execute application public static void main( String args[] ) { DrawPolygons application = new DrawPolygons(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); }

} // end class DrawPolygons 2002 Prentice Hall, Inc. All rights reserved. Outline Draw polygon2 to screen Specify PolygonDrawPolygons.java points and draw (filled) polygon3 to screen Line 37 Lines 39-42 Method addPoint adds pairs of x-y coordinates to Polygon Lines 45-49 Outline DrawPolygons.java Output 2002 Prentice Hall, Inc. All rights reserved. Java 2D API 11.8 Java 2D API Provides advanced 2D graphics capabilities java.awt java.awt.image java.awt.color java.awt.font.geom java.awt.print java.awt.image.renderable Uses class java.awt.Graphics2D Extends class java.awt.Graphics

Java 2D shapes Package java.awt.geom Ellipse2D.Double Rectangle2D.Double RoundRectangle2D.Double Arc3D.Double Lines2D.Double 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 28 29 30 31 32

33 34 35 Outline // Fig. 11.22: Shapes.java // Demonstrating some Java2D shapes // Java core packages import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.image.*; Shapes.java Lines 34-35 // Java extension packages import javax.swing.*; 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 ) { // call superclass's paint method super.paint( g ); // create 2D by casting g to Graphics2D Graphics2D g2d = ( Graphics2D ) g; Use GradientPaint to fill shape with gradient // draw 2D ellipse filled with a blue-yellow gradient g2d.setPaint( new GradientPaint( 5, 30, Color.blue, 35, 100, Color.yellow, true ) ); 2002 Prentice Hall, Inc. All rights reserved. 36 37 38 39

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 Fill ellipse with gradient Outline g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) ); // draw 2D rectangle in red g2d.setPaint( Color.red ); g2d.setStroke( new BasicStroke( 10.0f ) ); g2d.draw( new Rectangle2D.Double( 80, 30, 65, 100 ) ); Use BasicStroke to draw Shapes.java 2D red-border rectangle

// draw 2D rounded rectangle with a buffered background BufferedImage buffImage = new BufferedImage( 10, 10, BufferedImage.TYPE_INT_RGB ); Graphics2D gg = buffImage.createGraphics(); gg.setColor( Color.yellow ); // draw in yellow gg.fillRect( 0, 0, 10, 10 ); // draw a filled rectangle gg.setColor( Color.black ); // draw in black gg.drawRect( 1, 1, 6, 6 ); // draw a rectangle gg.setColor( Color.blue ); // draw in blue gg.fillRect( 1, 1, 3, 3 ); // draw a filled rectangle gg.setColor( Color.red ); // draw in red gg.fillRect( 4, 4, 3, 3 ); // draw a filled rectangle // paint buffImage onto the JFrame g2d.setPaint( new TexturePaint( buffImage, new Rectangle( 10, 10 ) ) ); g2d.fill( new RoundRectangle2D.Double( 155, 30, 75, 100, 50, 50 ) ); // draw 2D pie-shaped arc in white g2d.setPaint( Color.white ); g2d.setStroke( new BasicStroke( 6.0f ) ); g2d.draw( new Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) ); // draw 2D lines in green and yellow g2d.setPaint( Color.green ); 2002 Prentice Hall, Inc. All rights reserved. Line 36 BufferedImage produces 40-41 image Lines to be manipulated Lines 44-45 Lines 47-55 Draw texture into BufferedImage Lines 58-61 Lines 64-67

Use BufferedImage as texture for painting rounded rectangle Use Arc2D.PIE to draw white-border 2D pie-shaped arc 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 g2d.draw( new Line2D.Double( 395, 30, 320, 150 ) ); Outline Draw solid green line float dashes[] = { 10 }; g2d.setPaint( Color.yellow ); g2d.setStroke( new BasicStroke( 4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10, dashes, 0 ) ); g2d.draw( new Line2D.Double( 320, 30, 395, 150 ) ); } Lines 75-78 // execute application public static void main( String args[] ) { Shapes application = new Shapes();

application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } Shapes.java Draw dashed yellow line Linesolid 71 green line that crosses // end class Shapes 2002 Prentice Hall, Inc. All rights reserved. 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 28 29 30 31 32

33 34 35 // Fig. 11.23: Shapes2.java // Demonstrating a general path // Java core packages import java.awt.*; import java.awt.event.*; import java.awt.geom.*; Outline Shapes2.java Lines 31-34 // Java extension packages import javax.swing.*; public class Shapes2 extends JFrame { // set window's title bar String, background color // and dimensions public Shapes2() { super( "Drawing 2D Shapes" ); getContentPane().setBackground( Color.yellow ); setSize( 400, 400 ); setVisible( true ); } // draw general paths public void paint( Graphics g ) { // call superclass's paint method super.paint( g ); int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 }; int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 }; 2002 Prentice Hall, Inc. All rights reserved. x-y coordinates that comprise star 36 37 38 39 40 41

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 Graphics2D g2d = ( Graphics2D ) g; // create a star from a series of points GeneralPath star = new GeneralPath(); // set the initial coordinate of the General Path star.moveTo( xPoints[ 0 ], yPoints[ 0 ] ); GeneralPath is a shape Outline constructed from straight lines and complex curves Shapes2.java // create the star--this does not draw the star for ( int count = 1; count < xPoints.length; count++ ) star.lineTo( xPoints[ count ], yPoints[ count ] ); // close the shape star.closePath();

Line 39 Create star Lines 42-49 Lines 55-67 // translate the origin to (200, 200) g2d.translate( 200, 200 ); // rotate around origin and draw stars in random colors for ( int count = 1; count <= 20; count++ ) { // rotate coordinate system g2d.rotate( Math.PI / 10.0 ); // set random drawing color g2d.setColor( new Color( ( int ) ( Math.random() * 256 ), ( int ) ( Math.random() * 256 ), ( int ) ( Math.random() * 256 ) ) ); // draw filled star g2d.fill( star ); } } // end method paint 2002 Prentice Hall, Inc. All rights reserved. Draw filled, randomly colored star 20 times around origin 71 72 73 74 75 76 77 78 79 80 81 // execute application public static void main( String args[] ) { Shapes2 application = new Shapes2(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

} } // end class Shapes2 2002 Prentice Hall, Inc. All rights reserved. Outline Shapes2.java 11.10 (Optional Case Study) Thinking About Objects: Designing Interfaces With the UML Use UML to represent listener interfaces Class diagram modeling realizations Classes realize, or implement, interface behaviors Person realizes DoorListener In Java, class Person implements interface DoorListener Perso n - ID : Integer - mo ving : Boo lea n = true - lo cation : Loca tion + d oorOpened ( ) : void Perso n - ID : Integer - mo ving : Boo lea n = true - lo cation : Loca tion + d oorOpened ( ) : void inte rfa ce DoorListener + doo rOpe ne d( Doo rEvent : do orEvent ) : vo id + do orC lo sed( Do orEvent : d oorEve nt ) : void DoorListener 1 // Person.java 2 // Generated from Fig. 11.24 3 public class Person implements DoorListener { 4 5 // attributes 6 private int ID; 7 private boolean moving = true;

8 private Location location; 9 10 // constructor 11 public Person() {} 12 13 // methods of DoorListener 14 public void doorOpened( DoorEvent doorEvent ) {} 15 public void doorClosed( DoorEvent doorEvent ) {} 16 } 2002 Prentice Hall, Inc. All rights reserved. Outline Person.java Lines 3 and 14-15 Class Person must implement DoorListener methods Fig. 11.27 Class diagram that models realizations in the elevator model. PersonMoveListener ButtonListener DoorListener ElevatorModel LightListener BellListener Elevator ButtonListener DoorListener ElevatorShaft DoorListener

Person ElevatorMoveListener Door Light Bell Button Fig. 11.28 Class diagram for listener interfaces interfa ce Be llListener +b ellRang ( BellEvent : be llEvent ) : void interface ButtonListener +b uttonPresse d( ButtonEvent : b uttonEvent ) : void +b uttonReset( ButtonEvent : buttonEvent ) : void inte rface DoorListener + doo rOpe ne d( Doo rEvent : do orEvent ) : vo id + do orC lo sed( Do orEvent : d oorEve nt ) : void interfa ce ElevatorM oveListener + eleva to rArrived ( Eleva to rMo veEvent : e levatorMoveEvent ) : void + eleva to rDep arted ( ElevatorM ove Eve nt : eleva to rMo veEvent ) : void inte rface LightListener + lightTurne dOn( Lig htEvent : lig htEvent ) : vo id + lightTurne dOff( Lig htEvent : lig htEvent ) : vo id interfac e Perso nMoveListener +personC rea te d( PersonMoveEvent : p ersonM ove Event ) : vo id +personArrived ( Pe rsonM oveEvent : personMoveEvent ) : void +personDep arted ( PersonMoveEvent : pe rsonM oveEvent ) : void +personPresse dButton( PersonMoveEvent : personMo veEvent ) : vo id +personEntered( PersonMo veEvent : p erso nMoveEve nt ) : void +personExited( PersonMoveEvent : p erso nMoveEve nt ) : vo id

Recently Viewed Presentations

  • RePtiles

    RePtiles

    Reptile Circulation. Ectothermic - "cold-blooded" - have behaviors to keep them warm . 3-chambered heart with 2 atria, 1 ventricle partially divided by incomplete septum. 4-chambered heart in crocodiles (and birds) 2 aortic arches - left and right (birds have...
  • www.csd.uwo.ca

    www.csd.uwo.ca

    Welcome to PSAC Local 610 . Public Service Alliance of Canada (PSAC) is a parent union that represents over 180,000 employees in every province and territory in Canada and in locations around the world. As Graduate Teaching Assistants (GTAs) and...
  • Trouble with Britain - bcsc.k12.in.us

    Trouble with Britain - bcsc.k12.in.us

    Both President Madison and Thomas Jefferson wanted the United States to stay neutral or not take sides during that war. ... Burning of the White House. ... he noticed that the American flag was still flying high over Fort McHenry...
  • Chapter 3 Crystal growth, wafer fabrication and basic

    Chapter 3 Crystal growth, wafer fabrication and basic

    reciprocals of the intercepts of the plane with the x, y and z axes. For the (110) plane, it has intercepts with x, y, z-axis of 1, 1, (i.e. no intercept with z-axis).
  • chapter fourteen - University of North Carolina at Chapel Hill

    chapter fourteen - University of North Carolina at Chapel Hill

    Normative isomorphism: Professionals do it this way. Results from common training and professionalism. Today's Take-aways While competition is important, there is more than simply competition to the success of today's organizations. There are a variety of ways to explain inter-organizational...
  • Title

    Title

    Bubble Map Bubble maps are used for describing an object/topic, not to be confused with circle map Created with Kidspiration or Inspiration Double Bubble Map -is used for comparing and contrasting -helps students look closely and think deeply about two...
  • ONLINE CIVIC PARTICIPATION IN THE BUDGETING PROCESS 2013

    ONLINE CIVIC PARTICIPATION IN THE BUDGETING PROCESS 2013

    I'll start by analogizing . online civic engagement to . conventional civic engagement. Many view civic engagement as a spectrum. It can start with brainstorming on early stage topics at workshops & charrettes; and. it can evolve to specific feedback...
  • Design and Development of the Mars-Oz Base

    Design and Development of the Mars-Oz Base

    Concept Design Process - STEP 1 Define the project aims, scope of work and technical specification Mission statement or general aim NASA is to build a moon base to be visited regularly during the moon's daylight period. The construction will...