Chapter2 "Graphics & Java2D"
Chapter2 "Graphics & Java2D"
Introduction
http://java.comsci.us/tutorial/index.html Javasgraphicscapabilities:Drawing2Dshapes, Controllingcolorsandfonts; Java2DAPI(Moregraphicscapabilities):Drawingcustom 2Dshapes, Fillingshapes withcolors& patterns.
Oct 11
Oct 11
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
Oct 11
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 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.
6 CG_0702461 Ch02 Oct_11 Oct 11
1//TrytheCode:ShowColors.java 2//ThatDemonstratesColors. 3import java.awt.*;//Containsalloftheclassesforcreating //userinterfacesandforpaintinggraphicsandimages 4import javax.swing.*;/*Providesasetof"lightweight"(all Javalanguage)componentsthat,tothemaximumdegree possible,workthesameonallplatforms.*/ 6public class ShowColors extends JFrame { 8 //constructorsetswindow'stitlebarstring&dimensions 9 public ShowColors() 10 { 11 super("Usingcolors" ); 12 13 setSize(400,130 ); 14 setVisible(true );
7 CG_0702461Ch02Oct_11 Oct 11
15 16 17 18 19 20 21 22 23 24 25 26 27
8
} //drawrectanglesandStringsindifferentcolors public void paint(Graphicsg) { //callsuperclass's paintmethod super.paint(g); //setnewdrawingcolorusingintegers g.setColor(new Color(255,0,0 )); g.fillRect(25,25,100,20 ); g.drawString("CurrentRGB:" +g.getColor(),130,40 );
CG_0702461Ch02Oct_11
Oct 11
28 //setnewdrawingcolorusingfloats 29 g.setColor(new Color(0.0f,1.0f,0.0f )); 30 g.fillRect(25,50,100,20 ); 31 g.drawString("CurrentRGB:" +g.getColor(),130,65 ); 32 33 //setnewdrawingcolorusingstaticColorobjects 34 g.setColor(Color.BLUE ); 35 g.fillRect(25,75,100,20 ); 36 g.drawString("CurrentRGB:" +g.getColor(),130,90 ); 37 38 //displayindividualRGBvalues 39 Colorcolor =Color.MAGENTA; 40 g.setColor(color); 41 g.fillRect(25,100,100,20 );
9 CG_0702461Ch02Oct_11 Oct 11
42 g.drawString("RGBvalues:" +color.getRed()+"," + 43 color.getGreen()+"," +color.getBlue(),130,115 ); 44 45 }//endmethodpaint 46 47 //executeapplication 48 public static void main(Stringargs[]) 49 { 50 ShowColors application=new ShowColors(); 51 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 52 } }//endclassShowColors
10
CG_0702461Ch02Oct_11
Oct 11
1//TrytheCode:ShowColors2.java 2//ThatChoosescolorswithJColorChooser. 3import java.awt.*; 4import java.awt.event.*;/* Providesinterfacesandclassesfor dealingwithdifferenttypesofeventsfiredbyAWTcomponents/* 5import javax.swing.*; 6 7public class ShowColors2extends JFrame { 8 private JButton changeColorButton; 9 private Colorcolor =Color.LIGHT_GRAY; 10 private Containercontainer; 11 12 //setupGUI 13 public ShowColors2() 14 {
11 CG_0702461Ch02Oct_11 Oct 11
15 16 17 18 19 20 21 22 23 24 25 26 27 28
12
super("UsingJColorChooser" ); container=getContentPane(); container.setLayout(new FlowLayout()); //setupchangeColorButton ®isteritseventhandler changeColorButton =new JButton("ChangeColor" ); changeColorButton.addActionListener( new ActionListener(){//anonymousinnerclass //displayJColorChooser whenuserclicksbutton public void actionPerformed(ActionEvent event) {
CG_0702461Ch02Oct_11 Oct 11
29 30 31 32 33 34 35 36 37 38 39 40 41 42
13
43 44 container.add(changeColorButton ); 45 46 setSize(400,130 ); 47 setVisible(true ); 48 49 }//endShowColor2constructor 50 51 //executeapplication 52 public static void main(Stringargs[]) 53 { 54 ShowColors2application=new ShowColors2(); 55 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 56 } }//endclassShowColors2
14 CG_0702461Ch02Oct_11 Oct 11
15
CG_0702461Ch02Oct_11
Oct 11
FontControl
Class Font: Represents fonts that are used to render text in a visible way. A font provides the information needed to map sequences of characters to sequences of glyphs (a shape used to render a character/a sequence of characters) & to render sequences of glyphs on. Graphics and Component objects. Contains methods & constants for font control Fontconstructortakes3 arguments: Fontname:Monospaced, SansSerif,Serif,Calibri,etc. Fontstyle:Font.PLAIN, Font.ITALIC &Font.BOLD Fontsize:Measuredinpoints(1/72ofinch) Oct 11
16 CG_0702461 Ch02 Oct_11
Method or constant
Fontrelatedmethods&constants
Description
Creates a Font object with the specified font, style and size.
public int getStyle()
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. Graphics methods for manipulating Fonts
Font getFont() Returns a Font object reference representing the current font. void setFont( Font f ) Sets the current font to the font, style and size specified by the Font object refere
17
CG_0702461Ch02Oct_11
Oct 11
1//TrytheCode:Fonts.java 2//ThatUsesfonts. 3import java.awt.*; 4import javax.swing.*; 5 6public class Fontsextends JFrame{ 7 8 //setwindow'stitlebaranddimensions 9 public Fonts() 10 { 11 super("Usingfonts" ); 12 13 setSize(420,125 ); 14 setVisible(true ); 15 }
18 CG_0702461Ch02Oct_11 Oct 11
16 17 //displayStringsindifferentfontsandcolors 18 public void paint(Graphicsg) 19 { 20 //callsuperclass's paintmethod 21 super.paint(g); 22 23 //setfonttoSerif(Times),bold,12ptanddrawastring 24 g.setFont(new Font("Serif",Font.BOLD,12 )); 25 g.drawString("Serif12pointbold.",20,50 ); 26 27//setfonttoMonospaced (Courier),italic,24pt&drawastring 28 g.setFont(new Font("Monospaced",Font.ITALIC,24 )); 29 g.drawString("Monospaced 24pointitalic.",20,70 ); 30
19 CG_0702461Ch02Oct_11 Oct 11
31//setfonttoSansSerif(Helvetica),plain,14pt&drawastring 32 g.setFont(new Font("SansSerif",Font.PLAIN,14 )); 33 g.drawString("SansSerif14pointplain.",20,90 ); 34 35 //setfonttoSerif(Times),bold/italic,18pt& drawastring 36 g.setColor(Color.RED ); 37 g.setFont(new Font("Serif",Font.BOLD +Font.ITALIC,18 ) ); 38 g.drawString(g.getFont().getName()+"" + g.getFont().getSize()+ 39 "pointbolditalic.",20,110 ); 40 41 }//endmethodpaint 42
20 CG_0702461Ch02Oct_11 Oct 11
43 //executeapplication 44 public static void main(Stringargs[]) 45 { 46 Fontsapplication=new Fonts(); 47 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 48 } 49 50}//endclassFonts
21
CG_0702461Ch02Oct_11
Oct 11
Font metrics
Fontmetrics Height Descent (amountcharacterdipsbelowbaseline) Ascent (amountcharacterrisesabovebaseline) Leading (differencebetweendescentandascent)
22
Oct 11
FontMetrics methods
public int getAscent()
23
Oct 11
1//TrytheCode:Metrics.java 2 //FontMetrics&Graphicsmethodsusefulforobtainingfontmetrics. 3import java.awt.*; 4import javax.swing.*; 5 6public class Metricsextends JFrame{ 7 8 //setwindow'stitlebarStringanddimensions 9 public Metrics() 10 { 11 super("DemonstratingFontMetrics" ); 12 13 setSize(510,210 ); 14 setVisible(true );
24 CG_0702461Ch02Oct_11 Oct 11
15 16 17 18 19 20 21 22 23 24
} //displayfontmetrics public void paint(Graphicsg) { super.paint(g);//callsuperclass'spaintmethod g.setFont(new Font("SansSerif",Font.BOLD,12 )); FontMetricsmetrics=g.getFontMetrics(); g.drawString("Currentfont:" +g.getFont(),10,40 );
25
CG_0702461Ch02Oct_11
Oct 11
25g.drawString("Ascent:" +metrics.getAscent(),10,55 ); 26g.drawString("Descent:" +metrics.getDescent(),10,70 ); 27g.drawString("Height:" +metrics.getHeight(),10,85 ); 28g.drawString("Leading:" +metrics.getLeading(),10,100 ); 29 30Fontfont =new Font("Serif",Font.ITALIC,14 ); 31metrics=g.getFontMetrics(font); 32 g.setFont(font);
33g.drawString("Currentfont:" +font,10,130 ); 34 g.drawString("Ascent:" +metrics.getAscent(),10,145 ); 35g.drawString("Descent:" +metrics.getDescent(),10,160 ); 36 g.drawString("Height:" +metrics.getHeight(),10,175 ); 37 g.drawString("Leading:" +metrics.getLeading(),10,190 );
26 CG_0702461Ch02Oct_11 Oct 11
38 39 }//endmethodpaint 40 41 //executeapplication 42 public static void main(Stringargs[]) 43 { 44 Metricsapplication=new Metrics(); 45 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 46 }}//endclassMetrics
27
CG_0702461Ch02Oct_11
Oct 11
With that here are the predefined shapes that Java provides (lines, squares and circles) under the graphics object: Drawsa line,usingthecurrentcolor,betweenthepoints (x1,y1)&(x2,y2)inthisgraphicscontext'scoordinate system. drawLine(int x1,int y1,int x2,int y2) Drawstheoutlineofan oval.Setheightandwidthtothe samevaluefora circle. drawOval(int x,int y,int width,int height) Drawstheoutlineofthespecified rectangle. drawRect(int x,int y,int width,int height) Drawsthe text givenbythespecifiedstring,usingthis graphicscontext'scurrentfontandcolor. drawString(Stringstr,int x,int y)
29 CG_0702461 Ch02 Oct_11 Oct 11
D raws a rectangle o f the specified width and height . The top-left corner of the rectangle has the coordinates ( x , y ).
public v oid fi llRect ( int x, int y, int width , int height )
D raws a solid rectangle with the specified width and height . The top-left corner of the rectangle has the coordinate ( x , y ).
public v oid cl earRec t( in t x, int y, in t widt h, in t height )
D raws 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 v oid dr awRoun dRect ( int x, int y , int width , int he ight, int a rcWidt h, int arcH eight )
D raws a rectangle with rounded corners in the current color with the specified width and height . The arcWi d th and arcHeight determ ine the rounding of the corners (see Fig. 12.15).
public v oid fi llRoun dRect ( int x, int y , int width , int he ight, int a rcWidt h, int arcH eight )
D raws a solid rectangle with rounded corners in the current color with the specified width and height . The arcWidth and arcHeig ht determ ine the rounding of the corners (see Fig. 12.15).
30
Oct 11
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
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
31
Oct 11
1//TrytheCode:LinesRectsOvals.java 2//ThatDrawslines,rectanglesandovals. 3import java.awt.*; 4import javax.swing.*; 5 6public class LinesRectsOvals extends JFrame { 7 8 //setwindow'stitlebarStringanddimensions 9 public LinesRectsOvals() 10 { 11 super("Drawinglines,rectanglesandovals" ); 12 13 setSize(400,165 ); 14 setVisible(true ); 15 }
32 CG_0702461Ch02Oct_11 Oct 11
16 17 //displayvariouslines,rectanglesandovals 18 public void paint(Graphicsg) 19 { 20 super.paint(g);//callsuperclass's paintmethod 21 22 g.setColor(Color.RED ); 23 g.drawLine(5,30,350,30 ); 24 25 g.setColor(Color.BLUE ); 26 g.drawRect(5,40,90,55 ); 27 g.fillRect(100,40,90,55 ); 28 29 g.setColor(Color.CYAN );
33 CG_0702461Ch02Oct_11 Oct 11
30 31 32
g.fillRoundRect(195,40,90,55,50,50 ); g.drawRoundRect(290,40,90,55,20,20 );
43 //executeapplication 44 public static void main(Stringargs[]) 45 { 46 LinesRectsOvalsapplication=new LinesRectsOvals(); 47 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 48 }}//endclassLinesRectsOvals
35
CG_0702461Ch02Oct_11
Oct 11
Arcwidthandarcheightfor roundedrectangles
36
Oct 11
Ovalboundedbyarectangle
37
Oct 11
DrawingArcs
Arc:Portionofanovalmeasuredindegrees; Sweeps thenumberofdegreesinarcangle Sweepstartsatstartingangle: Counterclockwise sweepismeasureinpositive degrees Clockwise sweepismeasureinnegativedegrees
Positiveangles 90 Negativeangles 90 0
180
180
270
38 CG_0702461 Ch02 Oct_11
270
Oct 11
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.
39
Oct 11
1//TrytheCode:DrawArcs.java 2//ThatDrawsarcs 3import java.awt.*; 4import javax.swing.*; 5 6public class DrawArcsextends JFrame{ 7 8 //setwindow'stitlebarStringanddimensions 9 public DrawArcs() 10 { 11 super("DrawingArcs" ); 12 13 setSize(300,170 ); 14 setVisible(true ); 15 }
40 CG_0702461Ch02Oct_11 Oct 11
16 17 //drawrectanglesandarcs 18 public void paint(Graphicsg) 19 { 20 super.paint(g);//callsuperclass's paintmethod 21 22 //startat0andsweep360degrees 23 g.setColor(Color.YELLOW ); 24 g.drawRect(15,35,80,80 ); 25 g.setColor(Color.BLACK ); 26 g.drawArc(15,35,80,80,0,360 ); 27 28 //startat0andsweep110degrees 29 g.setColor(Color.YELLOW );
41 CG_0702461Ch02Oct_11 Oct 11
30 31 32 33 34 35 36 37 38 39 40 41 42 43
42
g.drawRect(100,35,80,80 ); g.setColor(Color.BLACK ); g.drawArc(100,35,80,80,0,110 ); //startat0andsweep270degrees g.setColor(Color.YELLOW ); g.drawRect(185,35,80,80 ); g.setColor(Color.BLACK ); g.drawArc(185,35,80,80,0,270 ); //startat0andsweep360degrees g.fillArc(15,120,80,40,0,360 ); //startat270andsweep90degrees
CG_0702461Ch02Oct_11 Oct 11
43
CG_0702461Ch02Oct_11
Oct 11
51 //executeapplication 52 public static void main(Stringargs[]) 53 { 54 DrawArcs application=new DrawArcs(); 55 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 56 }}//endclassDrawArcs
44
CG_0702461Ch02Oct_11
Oct 11
DrawingPolygonsandPolylines
Class Polygon Polygons: Multisided shapes; Polylines: Series of connected points; Java also provides drawing capabilities for polygons and polylines. Both are defined by a set of points (stored in parallel arrays of x and y coordinates). In both cases, each point is connected to the point after it, but in a polygon, last point is connected to the first The Polygon class provides two constructors: a default constructor an initializer constructor that takes arrays of coordinates (integers) and the logical size of those arrays: public Polygon(int[] xValues, int[] yValues, int numPoints) The Polygon class modifier addPoint() allows us to add a point by passing two arguments, the x and y coordinates, respectively. Consider an example to specify a triangle using default constructor: Polygon triangle; triangle = new Polygon(); triangle.addPoint(50, 100); triangle.addPoint(50, 400); triangle.addPoint(200, 400);
45 CG_0702461 Ch02 Oct_11 Oct 11
Graphicsmethodstodrawpolygons&class Polygonmethods
Method Description
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 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 )
46
Oct 11
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 )
47
Oct 11
1//TrytheCode:DrawPolygons.java 2//ThatDrawspolygons. 3import java.awt.*; 4import javax.swing.*; 5 6public class DrawPolygonsextends JFrame{ 7 8 //setwindow'stitlebarStringanddimensions 9 public DrawPolygons() 10 { 11 super("DrawingPolygons" ); 12 13 setSize(275,230 ); 14 setVisible(true ); 15 }
48 CG_0702461Ch02Oct_11 Oct 11
16 17 //drawpolygonsandpolylines 18 public void paint(Graphicsg) 19 { 20 super.paint(g);//callsuperclass's paintmethod 21 22 int xValues[]={20,40,50,30,20,15 }; 23 int yValues[]={50,50,60,80,80,60 }; 24 Polygonpolygon1=new Polygon(xValues,yValues,6 ); 25 26 g.drawPolygon(polygon1); 27 28 29
49
30 31 32 33 34 35 36 37 38 39 40 41 42 43
50
g.drawPolyline(xValues2,yValues2,7 ); int xValues3[]={120,140,150,190 }; int yValues3[]={40,70,80,60 }; g.fillPolygon(xValues3,yValues3,4 ); Polygonpolygon2=new Polygon(); polygon2.addPoint(165,135 ); polygon2.addPoint(175,150 ); polygon2.addPoint(270,200 ); polygon2.addPoint(200,220 ); polygon2.addPoint(130,180 );
CG_0702461Ch02Oct_11 Oct 11
44 45 g.fillPolygon(polygon2); 46 47 }//endmethodpaint 48 49 //executeapplication 50 public static void main(Stringargs[]) 51 { 52 DrawPolygons application=new DrawPolygons(); 53 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 54 }}//endclassDrawPolygons
51
CG_0702461Ch02Oct_11
Oct 11
1. Develop an interactive Java application that allows a user to draw various geometric shapes in Java 2D with different colors, including rectangles, round rectangles, ellipses, arcs, lines, quadratic curves, cubic curves, and polygons (Opposite Figure). A menu is used to select drawing shapes, and the user draws a particular shape on the screen by dragging the mouse. The drawings are persistent (they will not disappear when the window is repainted. 2. Develop an interactive Java 2D applet that draws a spinning sphere as demonstrated in the opposite figure? Note: S u b m i s s i o n i n c l u d e s : Hardcopy: Source Code, UML Documentation & Run for all options Softcopy: Source Code, UML Documentation & Run for all options CG_0702461 Ch02 Oct_11 52 Oct 11
PAIRSAssignment(15 Oct.2011)
th