Upload
mahmoud-r-erekat
View
214
Download
0
Embed Size (px)
Citation preview
8/3/2019 Lect2_JavaBasics
1/52
CG_0702461Ch02Oct_111
Chapter2Graphics&Java2D
Introduction;
Graphics
Contexts
and
Graphics
Objects
&
ColorControl;
FontControl;
Drawing
Lines,
Rectangles
&
Ovals;
DrawingArcs.
Oct 11
8/3/2019 Lect2_JavaBasics
2/52
http://java.comsci.us/tutorial/index.html
Javasgraphics
capabilities:
Drawing
2D
shapes,
Controllingcolorsandfonts;
Java2DAPI(Moregraphicscapabilities):Drawingcustom
2Dshapes,
Fillingshapes
withcolors&
patterns.
CG_0702461 Ch02 Oct_112
Introduction
Oct 11
http://java.comsci.us/tutorial/index.htmlhttp://java.comsci.us/tutorial/index.html8/3/2019 Lect2_JavaBasics
3/52
CG_0702461 Ch02 Oct_113
Javascoordinatesystem
Schemeforidentifyingallpointsonscreen;
Upperleft
corner
has
coordinates
(0,0);
Coordinatepointcomposedofxcoordinate&y
coordinate;
Javacoordinatesystem:Unitsaremeasuredinpixels:
Oct 11
8/3/2019 Lect2_JavaBasics
4/52
CG_0702461 Ch02 Oct_114
Graphics Contexts & Graphics Objects Graphicscontext
Enablesdrawing
on
screen
Graphicsobjectmanagesgraphicscontext
Controlshowinformationisdrawn
ClassGraphics
is
abstract
Cannotbeinstantiated
ContributestoJavasportability
ClassComponentmethodpainttakesGraphicsobject
publicvoid paint(Graphicsg)
Calledthrough
method
repaint;
Class Color: Defines methods & constants to manipulate
colors;
Colors are created from R, G & B components (RGBvalues).
Oct 11
8/3/2019 Lect2_JavaBasics
5/52
CG_0702461 Ch02 Oct_115
Color constants & their RGB valuesColor constant Color RGB valuepublic finalstatic Color ORANGE orange 255, 200, 0public 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, 255public 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, 255public 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
Oct 11
8/3/2019 Lect2_JavaBasics
6/52CG_0702461 Ch02 Oct_116
Color methods & color-related Graphics methodsMethod Description
Colorconstructors 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 asfloating-point values from 0.0 to 1.0.
publicint getRed()
Returns a value between 0 and 255 representing the red content.
publicint 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.
Graphicsmethods for manipulating Colors
public Color getColor()
Returns a Color object representing the current color for the graphicscontext.
public void setColor( Color c )
Sets the current color for drawing with the graphics context.
Oct 11
8/3/2019 Lect2_JavaBasics
7/52CG_0702461Ch02Oct_117
1 //TrytheCode:ShowColors.java
2 //ThatDemonstratesColors.
3
import java.awt.*;//Contains
all
of
the
classes
for
creating
//userinterfacesandforpaintinggraphicsandimages
4 import javax.swing.*;/*Providesasetof"lightweight"(all
Javalanguage)
components
that,
to
the
maximum
degree
possible,workthesameonallplatforms.*/
6 public class ShowColors extends JFrame {
8
//constructor
sets
window's
title
bar
string
&
dimensions
9 public ShowColors()
10 {
11
super("Using
colors" );
12
13 setSize(400,130 );
14 setVisible(true );
Oct 11
8/3/2019 Lect2_JavaBasics
8/52CG_0702461Ch02Oct_118
15 }
16
17 //drawrectanglesandStringsindifferentcolors
18 public void paint(Graphicsg)
19
{20 //callsuperclass's paintmethod
21 super.paint(g);
22
23 //setnewdrawingcolorusingintegers
24 g.setColor(new Color(255,0,0 ));
25
g.fillRect(25,
25,
100,
20 );
26 g.drawString("CurrentRGB:" +g.getColor(),130,40 );
27
Oct 11
8/3/2019 Lect2_JavaBasics
9/52CG_0702461Ch02Oct_119
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
//set
new
drawing
color
using
static
Color
objects
34 g.setColor(Color.BLUE );
35 g.fillRect(25,75,100,20 );
36
g.drawString("Current
RGB:
" +
g.getColor(),
130,
90 );
37
38 //displayindividualRGBvalues
39
Colorcolor =
Color.MAGENTA;
40 g.setColor(color);
41 g.fillRect(25,100,100,20 );
Oct 11
8/3/2019 Lect2_JavaBasics
10/52CG_0702461Ch02Oct_1110
42 g.drawString("RGBvalues:" +color.getRed()+"," +
43 color.getGreen()+"," +color.getBlue(),130,115 );
44
45 }//endmethodpaint
46
47
//execute
application
48 public static void main(Stringargs[])
49 {
50
ShowColors application=new ShowColors();
51 application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
52
} }//
end
class
ShowColors
Oct 11
8/3/2019 Lect2_JavaBasics
11/52CG_0702461Ch02Oct_1111
1 //TrytheCode:ShowColors2.java
2 //ThatChoosescolorswithJColorChooser.
3
import java.awt.*;
4 import java.awt.event.*;/* Providesinterfacesandclassesfor
dealingwithdifferenttypesofeventsfiredbyAWTcomponents/*
5
import javax.swing.*;
6
7 public class ShowColors2extends JFrame {
8 private JButton changeColorButton;
9 private Colorcolor =Color.LIGHT_GRAY;
10 private Containercontainer;
11
12 //setupGUI
13
public ShowColors2()14 {
Oct 11
8/3/2019 Lect2_JavaBasics
12/52CG_0702461Ch02Oct_1112
15 super("UsingJColorChooser" );
16
17
container=getContentPane();
18 container.setLayout(new FlowLayout());
19
20
//set
up
changeColorButton &
register
its
event
handler
21 changeColorButton =new JButton("ChangeColor" );
22 changeColorButton.addActionListener(
23
24 new ActionListener(){ //anonymousinnerclass
25
26 //displayJColorChooser whenuserclicksbutton
27 public void actionPerformed(ActionEvent event)
28
{
Oct 11
8/3/2019 Lect2_JavaBasics
13/52
CG_0702461Ch02Oct_1113
29 color=JColorChooser.showDialog(
30 ShowColors2.this,"Chooseacolor",color);
31
32 //setdefaultcolor,ifnocolorisreturned
33 if(color==null )
34
color=Color.LIGHT_GRAY;
35
36 //changecontentpane'sbackgroundcolor
37 container.setBackground(color);
38 }
39
40 }//endanonymousinnerclass
41
42
);
//
end
call
to
addActionListener
Oct 11
8/3/2019 Lect2_JavaBasics
14/52
CG_0702461Ch02Oct_1114
43
44 container.add(changeColorButton );
45
46 setSize(400,130 );
47 setVisible(true );
48
49 }//endShowColor2constructor
50
51
//execute
application
52 public static void main(Stringargs[])
53 {
54
ShowColors2application
=new ShowColors2();
55 application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
56
}
}//
end
class
ShowColors2
Oct 11
8/3/2019 Lect2_JavaBasics
15/52CG_0702461Ch02Oct_1115
HSB & RGB tabs of the
JColorChooser dialog
Oct 11
8/3/2019 Lect2_JavaBasics
16/52CG_0702461 Ch02 Oct_1116
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
controlFontconstructortakes3 arguments:
Fontname:Monospaced,
SansSerif,Serif,
Calibri,
etc.
Fontstyle:Font.PLAIN,
Font.ITALIC &Font.BOLD
Fontsize:Measuredinpoints(1/72ofinch)Oct 11
F t l t d th d & t t
8/3/2019 Lect2_JavaBasics
17/52CG_0702461Ch02Oct_1117
Fontrelated
methods
&
constants
Method or constant DescriptionFontconstants, constructors and methods for drawing polygonspublic final static intPLAIN
A constant representing a plain font style.public final static intBOLD
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 fonts 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.
Oct 11
Graphicsmethods for manipulating Fonts
Font getFont()
Returns aFont
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
8/3/2019 Lect2_JavaBasics
18/52
CG_0702461Ch02Oct_1118
1 //TrytheCode:Fonts.java
2 //ThatUsesfonts.
3
import java.awt.*;4 import javax.swing.*;
5
6
public class Fontsextends JFrame
{
7
8 //setwindow'stitlebaranddimensions
9
public Fonts()10 {
11 super("Usingfonts" );
12
13 setSize(420,125 );
14 setVisible(true );
15
}
Oct 11
8/3/2019 Lect2_JavaBasics
19/52
CG_0702461Ch02Oct_1119
16
17 //displayStringsindifferentfontsandcolors
18
public void paint(Graphics
g)
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
//set
font
to
Monospaced (Courier),
italic,
24pt&
draw
astring
28 g.setFont(new Font("Monospaced",Font.ITALIC,24 ));
29 g.drawString("Monospaced 24pointitalic.",20,70 );
30
Oct 11
8/3/2019 Lect2_JavaBasics
20/52
CG_0702461Ch02Oct_1120
31 //setfonttoSansSerif(Helvetica),plain,14pt&drawastring
32 g.setFont(new Font("SansSerif",Font.PLAIN,14 ));
33
g.drawString("SansSerif
14
point
plain.",
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
Oct 11
8/3/2019 Lect2_JavaBasics
21/52
CG_0702461Ch02Oct_1121
43 //executeapplication
44 public static void main(Stringargs[])
45
{
46 Fontsapplication=new Fonts();
47 application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
48 }
49
50
}//
end
class
Fonts
Oct 11
8/3/2019 Lect2_JavaBasics
22/52
CG_0702461 Ch02 Oct_1122
Font metrics Fontmetrics
Height
Descent (amountcharacterdipsbelowbaseline)
Ascent (amountcharacter
rises
above
baseline)
Leading (differencebetweendescentandascent)
Oct 11
FontMetrics & Graphics methods for
8/3/2019 Lect2_JavaBasics
23/52
CG_0702461 Ch02 Oct_1123
FontMetrics & Graphics methods for
obtaining font metricsMethod Description
FontMetricsmethods
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.
Graphicsmethods for getting a Fonts FontMetricspublic 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.
Oct 11
8/3/2019 Lect2_JavaBasics
24/52
CG_0702461Ch02Oct_1124
1 //TrytheCode:Metrics.java
2 //FontMetrics&Graphicsmethodsusefulforobtainingfontmetrics.
3
import java.awt.*;
4 import javax.swing.*;
5
6
public class Metricsextends JFrame
{
7
8 //setwindow'stitlebarStringanddimensions
9 public Metrics()
10 {
11 super("DemonstratingFontMetrics" );
12
13 setSize(510,210 );
14
setVisible(
true );
Oct 11
8/3/2019 Lect2_JavaBasics
25/52
CG_0702461Ch02Oct_1125
15 }
16
17
//display
font
metrics
18 public void paint(Graphicsg)
19 {
20
super.paint(g);
//
call
superclass's
paint
method
21
22 g.setFont(new Font("SansSerif",Font.BOLD,12 ));
23 FontMetricsmetrics=g.getFontMetrics();
24 g.drawString("Currentfont:" +g.getFont(),10,40 );
Oct 11
8/3/2019 Lect2_JavaBasics
26/52
CG_0702461Ch02Oct_1126
25 g.drawString("Ascent:" +metrics.getAscent(),10,55 );
26 g.drawString("Descent:" +metrics.getDescent(),10,70 );
27
g.drawString("Height:
" +
metrics.getHeight(),
10,
85 );
28 g.drawString("Leading:" +metrics.getLeading(),10,100 );
29
30
Fontfont =
new Font(
"Serif",
Font.ITALIC,
14 );
31 metrics=g.getFontMetrics(font);
32 g.setFont(font);
33 g.drawString("Currentfont:" +font,10,130 );
34 g.drawString("Ascent:" +metrics.getAscent(),10,145 );
35 g.drawString("Descent:" +metrics.getDescent(),10,160 );
36
g.drawString(
"Height:
" +
metrics.getHeight(),
10,
175 );37 g.drawString("Leading:" +metrics.getLeading(),10,190 );
Oct 11
8/3/2019 Lect2_JavaBasics
27/52
CG_0702461Ch02Oct_1127
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
Oct 11
8/3/2019 Lect2_JavaBasics
28/52
CG_0702461 Ch02 Oct_1128
Drawing Lines, Rectangles & Ovals Class Graphics: Provides methods for drawing lines,
rectangles and ovals;
All drawing methods require width & height parameters
Things to keep in mind:
1. Allthe
drawing
for
an
applet/application
is
done
inside
ofthe'public voidpaint(Graphicsg)' method.
2. Beforedrawinganything,call 'super.paint(g)',thisclears
thegraphicsobjectformoredrawing['g'isthegraphicsobject].
3. Point(0,0)isthelefttopofthegraphicsobjectg.
4. Use'g.setColor(Colorcolor)'beforedrawingashapetochangeitscolor.
5. Use
'setFont(Font
font)'
before
drawing
a
string
to
changeitsfont.Oct 11
i h h h h d fi d h h
8/3/2019 Lect2_JavaBasics
29/52
CG_0702461 Ch02 Oct_1129
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
samevalue
for
a 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
graphics
context's
current
font
and
color.drawString(Stringstr,int x,int y)Oct 11
Graphics methods that draw lines rectangles & ovals
8/3/2019 Lect2_JavaBasics
30/52
CG_0702461 Ch02 Oct_1130
Graphics methods that draw lines, rectangles & ovalsMethod Descriptionpublic void drawLine( int x1, int y1, int x2, int y2 )
Draw s a line between the po int (x1, y1) and the point (x2, y2).public void drawRect( int x, int y, int width, int height )
Draw s 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 )
Draw s a solid rectangle with the specified width and height . The top-left
corner o f the rectangle has the coordinate (x, y).
public void clearRect( int x, int y, int width, int height )
Draw s 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 )
Draw s 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 )
Draw s a solid rectangle with rounded corners in the current color with the
specified width and height . The arcWidth and arcHeight determine the
round ing of the corners (see Fig. 12.15).
Oct 11
8/3/2019 Lect2_JavaBasics
31/52
CG_0702461 Ch02 Oct_1131
Method Descriptionpublic 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. Thebounding 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
Oct 11
8/3/2019 Lect2_JavaBasics
32/52
CG_0702461Ch02Oct_1132
1 //TrytheCode:LinesRectsOvals.java
2 //ThatDrawslines,rectanglesandovals.
3
import java.awt.*;4 import javax.swing.*;
5
6
public 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
}
Oct 11
8/3/2019 Lect2_JavaBasics
33/52
CG_0702461Ch02Oct_1133
16
17 //displayvariouslines,rectanglesandovals
18
public void paint(Graphics
g)
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 );
Oct 11
8/3/2019 Lect2_JavaBasics
34/52
CG_0702461Ch02Oct_1134
30 g.fillRoundRect(195,40,90,55,50,50 );
31 g.drawRoundRect(290,40,90,55,20,20 );
32
33
g.setColor(Color.YELLOW );
34 g.draw3DRect(5,100,90,55,true );
35 g.fill3DRect(100,100,90,55,false );
36
37 g.setColor(Color.MAGENTA );
38 g.drawOval(195,100,90,55 );
39 g.fillOval(290,100,90,55 );
40
41
}
//
end
method
paint42
Oct 11
8/3/2019 Lect2_JavaBasics
35/52
CG_0702461Ch02Oct_1135
43 //executeapplication
44 public static void main(Stringargs[])
45
{
46 LinesRectsOvalsapplication=new LinesRectsOvals();
47 application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
48 }}//endclassLinesRectsOvals
Oct 11
A idth d h i ht f
8/3/2019 Lect2_JavaBasics
36/52
CG_0702461 Ch02 Oct_1136
Arcwidthandarcheightfor
rounded
rectangles
Oct 11
8/3/2019 Lect2_JavaBasics
37/52
CG_0702461 Ch02 Oct_1137
Ovalboundedbyarectangle
Oct 11
D i A
8/3/2019 Lect2_JavaBasics
38/52
Arc:
Portion
of
an
oval
measured
in
degrees; Sweeps thenumberofdegreesinarcangle Sweepstartsatstartingangle:
Counterclockwise sweepis
measure
in
positive
degrees
Clockwise sweepismeasureinnegativedegrees
CG_0702461 Ch02 Oct_1138
DrawingArcs
90
0180
270
Positiveangles
90
0180
270
Negativeangles
Oct 11
8/3/2019 Lect2_JavaBasics
39/52
CG_0702461 Ch02 Oct_1139
Graphics methods for drawing arcs
Method Descriptionpublic 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.
Oct 11
8/3/2019 Lect2_JavaBasics
40/52
CG_0702461Ch02Oct_1140
1 //TrytheCode:DrawArcs.java
2 //ThatDrawsarcs
3
import java.awt.*;4 import javax.swing.*;
5
6
public class DrawArcsextends JFrame
{
7
8 //setwindow'stitlebarStringanddimensions
9
public DrawArcs()10 {
11 super("DrawingArcs" );
12
13 setSize(300,170 );
14 setVisible(true );
15 }
Oct 11
8/3/2019 Lect2_JavaBasics
41/52
CG_0702461Ch02Oct_1141
16
17 //drawrectanglesandarcs
18
public void paint(Graphics
g)
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 );
Oct 11
8/3/2019 Lect2_JavaBasics
42/52
CG_0702461Ch02Oct_1142
30 g.drawRect(100,35,80,80 );
31 g.setColor(Color.BLACK );
32
g.drawArc(100,
35,
80,
80,
0,
110 );
33
34 //startat0andsweep 270degrees
35
g.setColor(Color.YELLOW );
36 g.drawRect(185,35,80,80 );
37 g.setColor(Color.BLACK );
38
g.drawArc(185,
35,
80,
80,
0,
270 );
39
40 //startat0andsweep360degrees
41 g.fillArc(15,120,80,40,0,360 );
42
43
//
start
at
270
and
sweep
90
degrees
Oct 11
8/3/2019 Lect2_JavaBasics
43/52
CG_0702461Ch02Oct_1143
44 g.fillArc(100,120,80,40,270,90 );
45
46
//start
at
0and
sweep
270
degrees
47 g.fillArc(185,120,80,40,0,270 );
48
49
}//
end
method
paint
50
Oct 11
8/3/2019 Lect2_JavaBasics
44/52
CG_0702461Ch02Oct_1144
51 //executeapplication
52 public static void main(Stringargs[])
53
{
54 DrawArcs application=new DrawArcs();
55 application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
56 }}//endclassDrawArcs
Oct 11
Drawing Polygons and Polylines
8/3/2019 Lect2_JavaBasics
45/52
CG_0702461 Ch02 Oct_1145
DrawingPolygons
and
Polylines
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
ofxand ycoordinates). 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 constructoran 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 xand ycoordinates, 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);
Oct 11
Graphics methods to draw polygons & class
8/3/2019 Lect2_JavaBasics
46/52
CG_0702461 Ch02 Oct_1146
p
p yg
PolygonmethodsMethod DescriptionGraphicsmethods for drawing polygons
public void drawPolygon( int xPoints[], int yPoints[], int points )
Draws a polygon. Thex-coordinate of each point is specified in the xPoints
array and they-coordinate of each point is specified in the yPoints array. The
last argument specifies the number ofpoints. This method draws a closed
polygon. If the last point is different from the first point, the polygon is closedby 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. Thex-coordinate of each point isspecified in the xPoints array and they-coordinate of each point is specified in
the yPoints array. The last argument specifies the number ofpoints. 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. Thex-coordinate of each point is specified in the
xPoints array and they-coordinate of each point is specified in the yPointsarray. The last argument specifies the number ofpoints. 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.
Oct 11
8/3/2019 Lect2_JavaBasics
47/52
CG_0702461 Ch02 Oct_1147
Polygonconstructors and methodspublic 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 anx-coordinate from xValues and ay-coordinate
from yValues.
publicvoid addPoint( int x, int y )
Adds pairs ofx- andy-coordinates to the Polygon.
Oct 11
1 // T th C d D P l j
8/3/2019 Lect2_JavaBasics
48/52
CG_0702461Ch02Oct_1148
1 //TrytheCode:DrawPolygons.java
2 //ThatDrawspolygons.
3
import java.awt.*;4 import javax.swing.*;
5
6
public class DrawPolygonsextends JFrame
{
7
8 //setwindow'stitlebarStringanddimensions
9
public DrawPolygons()10 {
11 super("DrawingPolygons" );
12
13 setSize(275,230 );
14 setVisible(true );
15
}
Oct 11
16
8/3/2019 Lect2_JavaBasics
49/52
CG_0702461Ch02Oct_1149
16
17 //drawpolygonsandpolylines
18
public void paint(Graphics
g)
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 int xValues2[]={70,90,100,80,70,65,60 };
29 int yValues2[]={100,100,110,110,130,110,90 }Oct 11
30
8/3/2019 Lect2_JavaBasics
50/52
CG_0702461Ch02Oct_1150
31 g.drawPolyline(xValues2,yValues2,7 );
32
33 int xValues3[]={120,140,150,190 };
34 int yValues3[]={40,70,80,60 };
35
36 g.fillPolygon(xValues3,yValues3,4 );
37
38
Polygonpolygon2
=new Polygon();
39 polygon2.addPoint(165,135 );
40 polygon2.addPoint(175,150 );
41 polygon2.addPoint(270,200 );
42 polygon2.addPoint(200,220 );
43 polygon2.addPoint(130,180 );
Oct 11
8/3/2019 Lect2_JavaBasics
51/52
CG_0702461Ch02Oct_1151
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
Oct 11
PAIRS Assignment (15th Oct 2011)
8/3/2019 Lect2_JavaBasics
52/52
1. Develop an interactive Java application that allows a user
to draw various geometric shapes in Java 2D with differentcolors, including rectangles, round rectangles, ellipses,arcs, lines, quadratic curves, cubic curves, andpolygons (Opposite Figure). A menu is used toselect drawing shapes, and the user draws aparticular shape on the screen by dragging themouse. 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
PAIRSAssignment(15 Oct.2011)