Tải bản đầy đủ - 0 (trang)
Chapter 12. Graphics and Java 2D™

Chapter 12. Graphics and Java 2D™

Tải bản đầy đủ - 0trang

Chapter12.GraphicsandJava2D™

Onepictureisworthtenthousandwords.

Chineseproverb

Treatnatureintermsofthecylinder,thesphere,

thecone,allinperspective.

PaulCézanne

Colors,likefeatures,followthechangesofthe

emotions.

PabloPicasso

Nothingeverbecomesrealtillitisexperiencedeven

aproverbisnoproverbtoyoutillyourlifehas

illustratedit.

JohnKeats

OBJECTIVES

Inthischapteryouwilllearn:

Tounderstandgraphicscontextsandgraphicsobjects.

Tounderstandandbeabletomanipulatecolors.

Tounderstandandbeabletomanipulatefonts.

TousemethodsofclassGraphicstodrawlines,rectangles,

rectangleswithroundedcorners,three-dimensional



rectangles,ovals,arcsandpolygons.

TousemethodsofclassGraphics2DfromtheJava2DAPIto

drawlines,rectangles,rectangleswithroundedcorners,

ellipses,arcsandgeneralpaths.

TobeabletospecifyPaintandStrokecharacteristicsof

shapesdisplayedwithGraphics2D.



[Page596]

Outline

12.1Introduction

12.2GraphicsContextsandGraphicsObjects

12.3ColorControl

12.4FontControl

12.5DrawingLines,RectanglesandOvals

12.6DrawingArcs

12.7DrawingPolygonsandPolylines

12.8Java2DAPI

12.9Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises



Exercises







[Page596(continued)]



12.1.Introduction

Inthischapter,weoverviewseveralofJava'scapabilitiesfor

drawingtwo-dimensionalshapes,controllingcolorsand

controllingfonts.OneofJava'sinitialappealswasitssupport

forgraphicsthatenabledprogrammerstovisuallyenhancetheir

applications.Javanowcontainsmanymoresophisticated

drawingcapabilitiesaspartoftheJava2D™API.Thischapter

beginswithanintroductiontomanyofJava'soriginaldrawing

capabilities.NextwepresentseveralofthemorepowerfulJava

2Dcapabilities,suchascontrollingthestyleoflinesusedto

drawshapesandthewayshapesarefilledwithcolorand

patterns.[Note:Severalconceptscoveredinthischapterhave

alreadybeencoveredintheoptionalGUIandGraphicsCase

StudyofChapters310.So,somematerialwillberepetitiveif

youreadthecasestudy.Youdonotneedtoreadthecasestudy

tounderstandthischapter.]

Figure12.1showsaportionoftheJavaclasshierarchythat

includesseveralofthebasicgraphicsclassesandJava2DAPI

classesandinterfacescoveredinthischapter.ClassColor

containsmethodsandconstantsformanipulatingcolors.Class

JComponentcontainsmethodpaintComponent,whichwillbeusedto

drawgraphicsonacomponent.ClassFontcontainsmethods

andconstantsformanipulatingfonts.ClassFontMetrics

containsmethodsforobtainingfontinformation.ClassGraphics

containsmethodsfordrawingstrings,lines,rectanglesand

othershapes.ClassGraphics2D,whichextendsclassGraphics,is

usedfordrawingwiththeJava2DAPI.ClassPolygoncontains

methodsforcreatingpolygons.Thebottomhalfofthefigure

listsseveralclassesandinterfacesfromtheJava2DAPI.Class

BasicStrokehelpsspecifythedrawingcharacteristicsoflines.

ClassesGradientPaintandTexturePainthelpspecifythe

characteristicsforfillingshapeswithcolorsorpatterns.Classes



GeneralPath,Line2D,Arc2D,Ellipse2D,Rectangle2DandRoundRectangle2D



representseveralJava2Dshapes.[Note:Webeginthechapter

bydiscussionJava'soriginalgraphicscapabilities,thenmoveon

totheJava2DAPI.However,itisimportanttounderstandthat

theclassesdiscussedaspartofJava'soriginalgraphics

capabilitiesarenowalsoconsideredtobepartoftheJava2D

API.]



Figure12.1.Classesandinterfacesusedinthis

chapterfromJava'soriginalgraphicscapabilities

andfromtheJava2DAPI.[Note:ClassObject

appearsherebecauseitisthesuperclassofthe

Javaclasshierarchy.]

(Thisitemisdisplayedonpage597intheprintversion)



[Viewfullsizeimage]



TobegindrawinginJava,wemustfirstunderstandJava's

coordinatesystem(Fig.12.2),whichisaschemefor

identifyingeverypointonthescreen.Bydefault,theupper-left

cornerofaGUIcomponent(e.g.,awindow)hasthecoordinates

(0,0).Acoordinatepairiscomposedofanx-coordinate(the

horizontalcoordinate)anday-coordinate(thevertical



coordinate).Thex-coordinateisthehorizontaldistance

movingrightfromtheleftofthescreen.They-coordinateisthe

verticaldistancemovingdownfromthetopofthescreen.The

x-axisdescribeseveryhorizontalcoordinate,andthey-axis

describeseveryverticalcoordinate.



[Page598]

Figure12.2.Javacoordinatesystem.Unitsare

measuredinpixels.



[Viewfullsizeimage]



Textandshapesaredisplayedonthescreenbyspecifying

coordinates.Thecoordinatesareusedtoindicatewhere

graphicsshouldbedisplayedonascreen.Coordinateunitsare

measuredinpixels.Apixelisadisplaymonitor'ssmallestunit

ofresolution.



PortabilityTip12.1

Differentdisplaymonitorshavedifferentresolutions(i.e.,

thedensityofthepixelsvaries).Thiscancausegraphics

toappeartobedifferentsizesondifferentmonitorsoron

thesamemonitorwithdifferentsettings.







[Page598(continued)]



12.2.GraphicsContextsandGraphicsObjects

AJavagraphicscontextenablesdrawingonthescreen.A

Graphicsobjectmanagesagraphicscontextanddrawspixelson

thescreenthatrepresenttextandothergraphicalobject(e.g.,

lines,ellipses,rectanglesandotherpolygons).Graphicsobjects

containmethodsfordrawing,fontmanipulation,color

manipulationandthelike.Everyapplicationwehaveseenin

thetextthatperformsdrawingonthescreenhasusedthe

Graphicsobjectg(theargumenttothepaintComponentmethodofa

componentsuchasaJPanel)tomanagetheapplication's

graphicscontext.

ClassGraphicsisanabstractclass(i.e.,Graphicsobjectscannotbe

instantiated).ThiscontributestoJava'sportability.Because

drawingisperformeddifferentlyoneveryplatformthat

supportsJava,therecannotbejustoneimplementationofthe

drawingcapabilitiesonallsystems.Forexample,thegraphics

capabilitiesthatenableaPCrunningMicrosoftWindowstodraw

arectanglearedifferentfromthosethatenableaLinux

workstationtodrawarectangleandtheyarebothdifferentfrom

thegraphicscapabilitiesthatenableaMacintoshtodrawa

rectangle.WhenJavaisimplementedoneachplatform,a

subclassofGraphicsiscreatedthatimplementsthedrawing

capabilities.Thisimplementationishiddenfromusbyclass

Graphics,whichsuppliestheinterfacethatenablesustouse

graphicsinaplatform-independentmanner.

ClassComponentisthesuperclassformanyoftheclassesinthe

java.awtpackage.(WediscussedclassComponentinChapter11.)

ClassJComponent,whichinheritsindirectlyfromclassComponent,

containsapaintComponentmethodthatcanbeusedtodraw

graphics.MethodpaintComponenttakesaGraphicsobjectasan

argument.ThisobjectispassedtothepaintComponentmethodby



thesystemwhenalightweightSwingcomponentneedstobe

repainted.TheheaderforthepaintComponentmethodis



[Page599]

publicvoidpaintComponent(Graphicsg)



ParametergreceivesareferencetoaninstanceofthesystemspecificsubclassthatGraphicsextends.Theprecedingmethod

headershouldlookfamiliartoyouitisthesameoneweusedin

someoftheapplicationsinChapter11.Actually,classJComponent

isasuperclassofJPanel.ManycapabilitiesofclassJPanelare

inheritedfromclassJComponent.

MethodpaintComponentisseldomcalleddirectlybythe

programmerbecausedrawinggraphicsisanevent-driven

process.WhenaGUIapplicationexecutes,theapplication

containercallsmethodpaintComponentforeachlightweight

componentastheGUIisdisplayed.ForpaintComponenttobe

calledagain,aneventmustoccur(suchascoveringand

uncoveringthecomponentwithanotherwindow).

IftheprogrammerneedstohavepaintComponentexecute(i.e.,if

theprogrammerwantstoupdatethegraphicsdrawnonthe

Swingcomponent),acallismadetomethodrepaint,whichis

inheritedbyallJComponentsindirectlyfromclassComponent

(packagejava.awt).Methodrepaintisfrequentlycalledbythe

programmertorequestacalltomethodpaintComponent.Method

repaintshouldnotbeoverridden,becauseitperformssome

system-dependenttasks.Theheaderforrepaintis

publicvoidrepaint()



[Page599(continued)]



12.3.ColorControl

ClassColordeclaresmethodsandconstantsformanipulating

colorsinaJavaprogram.Thepredeclaredcolorconstantsare

summarizedinFig.12.3,andseveralcolormethodsand

constructorsaresummarizedinFig.12.4.Notethattwoofthe

methodsinFig.12.4areGraphicsmethodsthatarespecificto

colors.

Figure12.3.ColorconstantsandtheirRGBvalues.

(Thisitemisdisplayedonpage600intheprintversion)

Colorconstant



Color



RGBvalue



publicfinalstaticColorRED



red



255,0,0



publicfinalstaticColorGREEN



green



0,255,0



publicfinalstaticColorBLUE



blue



0,0,255



publicfinalstaticColorORANGE



orange



255,200,0



publicfinalstaticColorPINK



pink



255,175,175



publicfinalstaticColorCYAN



cyan



0,255,255



publicfinalstaticColorMAGENTA



magenta



255,0,255



publicfinalstaticColorYELLOW



yellow



255,255,0



publicfinalstaticColorBLACK



black



0,0,0



publicfinalstaticColorWHITE



white



255,255,255



publicfinalstaticColorGRAY



gray



128,128,128



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 12. Graphics and Java 2D™

Tải bản đầy đủ ngay(0 tr)

×