Anda di halaman 1dari 7

Java

Microsoft&.NET
Mobile
Android
OpenSource
Cloud
Database
Architecture
Other
Slideshows
ProjectManagement
PHP
Perl
Ruby
Services
OtherLanguages
Whitepapers
ResearchCenter
NEW:Slideshows

May26,2016
HotTopics:
prev
Android
Java
Microsoft&.NET
Cloud
OpenSource
PHP
Database
next

Developer.com
Java
Data&Java
ReadMoreinData&Java
Manyorganizationshaveadoptedthecloud.ReadabouttheircloudsolutionsinoureBookandwhatyoucandoforyourbusiness.

UsingGraphicsinJavaFX
March9,2015
ByManojDebnath
Bio
SendEmail
MoreArticles
Tweet

JavaFXisbuiltprimarilytocreateanddeliverrichInternetapplications(RIAs)uniformly,acrossavariegatedplatform.Apartfromitscoreutility,
JavaFXisbundledwithasetofAPIsthatnotonlysupportbasicgraphicsprogrammingbutalsosomeofthehighlevel3DAPIsasapartofthecore
SDK.TheeaseandsimplicityofgraphicsprogrammingwithJavaFXisremarkablewhencomparedwithsomeofthestalwartsinthisarena,suchas
theJava3Dlibrary.BecauseJavaFXisfocusedonanUIdevelopment,itprovidessomeexcellentfeaturesfromthegroundupinthegraphicsarena
inparticular.Let'sexploresomeofitsfeatures.

JavaFXfromtheGroundUp
Beforedelvingintocode,wemustunderstandsomeofthebasicpackagesandclassesintheSDKAPIclasshierarchy.Thereareafewcommon
classes,interplayingacrucialroleandarethebasisofkickstartingagraphicscodeenvironment.Theycanbebetterunderstood,Ibelieve,ifwedraw
ananalogy.Let'screateoneaswegoalong.
Thejavafx.stagepackagecontainsthefollowing:

AStageclass,whichisatoplevelUIcontainer.Imagineitasthetheatricalstageofthedramacalledgraphicsprogramming.
AScreenclass,whichrepresentsdisplayparameterssuchassizeofthestage,resolution,andsoforth.
5ProvenWaystoMotivateandRetainYourTechnologyTeam

DownloadNow

Thejavafx.scenepackage(mostlyused)containstheseitems:
ASceneclass,whichisthesecondlevelcontainerwheretheacttakesplace.Itissimilartoasceneofthedramainactionoranactinmotion.
ANodeclassisanabstractbaseclassforallthegraphicalnodesinJavaFX,suchastext,images,media,shapes,andsoon.Theyarethe
actors.
AGroupclassisthesubclassofNode,whosepurposeistogroupseveralnodeobjectsintoasingleact.
ACanvasclassisbasicallyaNodesubclasswhichprovidesanAPItodrawshapesusingasetofgraphicscommands.Theadvantageof
CanvasisthatwecanobtainitsGraphicsContextandinvokedrawingoperationstorendercustomshapesonscreen.
Postacomment
EmailArticle
PrintArticle
ShareArticles
Digg
del.icio.us
Slashdot
DZone
Reddit
StumbleUpon
Facebook
FriendFeed
Furl
Newsvine
Google
LinkedIn
MySpace
Technorati
Twitter
YahooBuzz
Now,let'srephrasetheanalogy:Theabstractiondrama(graphicsprogramming)isdefinedbyseveralactors(Nodes),clubbedforinteraction(Group)
accordingtothescript(Scene),dramatisedonastage(Stage),whereourviewpoint(Screen)isdefinedbytheangle/distanceofthestagefromthe
gallery.
Observeinthefollowingcodehowactors(Nodeobjects:LineandTextobjects)aregrouped(asaGroupwithchildren)inascene(Sceneobject)and
displayedinastage(Stageobject).Application.launchexecutesthestartmethodimplicitlyandthedramaiscomplete.
//...importstatements
publicclassBareBoneGraphicsextendsApplication{
publicstaticvoidmain(String[]args){
Application.launch(args);
}
@Override
publicvoidstart(StageprimaryStage)throwsException{
primaryStage.setTitle("GraphicsinJavaFX");
Grouproot=newGroup();
Scenescene=newScene(root,300,250,Color.WHITE);
root.getChildren().add(newText(scene.getWidth()/2,
scene.getHeight()/2,"GraphicsisFun"));
root.getChildren().add(newLine(0,5,scene.getWidth(),5));
root.getChildren().add(newLine(5,0,5,scene.getHeight()));
primaryStage.setScene(scene);
primaryStage.show();
}
}

Listing1:AbareboneJavaFXgraphicsprogram

WorkingwithText
RelatedArticles
NewCoreFeaturesinJava8
StartUsingJavaLambdaExpressions
HowtoHireaJavaDeveloper
Textrenderingisoneofthecommonaspectswhenweplaywithgraphics.Wecanapplyseveralparameterstodisplaytextinascenewithavariation
offont,color,stroke,fill,androtate,andprovidesomeeffectssuchasshadowandthelike.Thefollowingcodedrawstextwiththehelpofa
concreteNodeclass,Text.Thecharactersaredisplayedrandomlywithrandomrotation.AnotherTextobjectisdisplayedwithashadoweffect.
//...importstatements
publicclassRenderingTextextendsApplication{
publicstaticvoidmain(String[]args){

Application.launch(args);
}
@Override
publicvoidstart(StageprimaryStage)throwsException{
primaryStage.setTitle("GraphicsinJavaFX");
Grouproot=newGroup();
Scenescene=newScene(root,650,450,Color.WHITE);
Randomrandom=newRandom(System.currentTimeMillis());
for(inti=0;i<500;i++){
Texttext=newText(random.nextInt((int)
scene.getWidth()),
random.nextInt((int)scene.getHeight()),
newCharacter((char)random.nextInt(255)).toString());
text.setFont(Font.font("Serif",random.nextInt(30)));
text.setFill(Color.rgb(random.nextInt(255),
random.nextInt(255),random.nextInt(255),0.5));
root.getChildren().add(text);
}
Texttext2=newText(60,
scene.getHeight()/2,"GraphicsisFun!");
text2.setFont(Font.font("Serif",FontWeight.EXTRA_BOLD,
FontPosture.REGULAR,60));
text2.setFill(Color.RED);
text2.setFontSmoothingType(FontSmoothingType.LCD);
DropShadowshadow=newDropShadow();
shadow.setOffsetX(2.0f);
shadow.setOffsetY(2.0f);
shadow.setColor(Color.BLACK);
shadow.setRadius(7);
text2.setEffect(shadow);
text2.setStroke(Color.DARKRED);
root.getChildren().add(text2);
primaryStage.setScene(scene);
primaryStage.show();
}
}

Listing2:Manipulatingtextrenderinginascene

Figure1:OutputofListing2

WorkingwithShapes
JavaFXprovidesanAPItodrawboth2Dand3Dshapes.3Dshapesareabitmorecomplex,whereconceptssuchasprojection,cameraangle,
differenttypesoflight,andshadingtechniquescomeintoplay.Letusputthatasidefornowandconcentrateonhowwecanmanipulate2Dshapes.
Thebasic2Dshapescanbeusedtodrawmorecomplexoneswhenusedappropriately.
Inthefollowingexample,Canvasisusedasthebasicdrawingcontainer.Observehoweasyitistomanipulateshapeswiththehelpofthe
GraphicsContextobject.
publicclassDrawingShapesextendsApplication{
publicstaticvoidmain(String[]args){
Application.launch(args);
}
@Override
publicvoidstart(StageprimaryStage)throwsException{
primaryStage.setTitle("GraphicsinJavaFX");
Grouproot=newGroup();
Canvascanvas=newCanvas(650,600);
GraphicsContextgc=canvas.getGraphicsContext2D();
draw2DShapes(gc);
root.getChildren().add(canvas);
primaryStage.setScene(newScene(root));
primaryStage.show();
}
privatevoiddraw2DShapes(GraphicsContextgc){
doublewidth=gc.getCanvas().getWidth();
doubleheight=gc.getCanvas().getHeight();
Randomrandom=newRandom(System.currentTimeMillis());
gc.setFill(Color.rgb(random.nextInt(255),random.nextInt(255),

random.nextInt(255),0.9));
gc.translate(width/2,height/2);
for(inti=0;i<60;i++){
gc.rotate(6.0);
gc.setFill(Color.rgb(random.nextInt(255),random.nextInt(255),
random.nextInt(255),0.9));
gc.fillOval(10,60,30,30);
random.nextInt(255),
random.nextInt(255),0.9));
gc.strokeOval(60,60,30,30);
gc.setFill(Color.rgb(random.nextInt(255),random.nextInt(255),
random.nextInt(255),0.9));
gc.fillRoundRect(110,60,30,30,10,10);
gc.setFill(Color.rgb(random.nextInt(255),random.nextInt(255),
random.nextInt(255),0.9));
gc.fillPolygon(
newdouble[]{105,117,159,123,133,105,77,87,51,93},
newdouble[]{150,186,186,204,246,222,246,204,186,186},10);
}
}
}

Listing3:Manipulating2DshapeswithGraphicsContextinaCanvas

Figure2:OutputofListing3

Conclusion
IfyouintendtouniteboththeworldofGUIprogrammingwithgraphicsandanimation,JavaFXistherightplatform.Apartfromitsbusinessutility,
graphicsprogrammingisalwaysfuninanyplatformorlanguage.Thethingthatmattersisthedeterminantofhowsteepthelearningcurveis.
JavaFXundoubtedlyprovidesasimpleandintuitiveAPItoworkwith,makingthelearningcurvealmostflat.AbeginnertointermediateJava
programmerwithalittleknowledgeofcomputergraphicscandoamazingthingsinJavaFX.Lastbutnotleast,withtheinclusionof3DAPIs,
JavaFXnowhasanotherfeatheronitshatKudos!totheFXteam.Thisarticlemerelyscratchedthesurfacewe'llexploremoreinfuturearticles
likethis.Staytuned.
Tags:Java,RIA,JavaFX,SDK,graphics,textrendering

2Comments(clicktoaddyourcomment)
ByglazOctober15201502:53PDT
Thankyou
ByJorgeJuly23201516:22PDT

Replytothiscomment

Thanksalot!thispostwasreallyusefulforme!
Replytothiscomment

CommentandContribute

Yourname/nickname
Youremail
Subject

(Maximumcharacters:1200).Youhave 1200

charactersleft.

Typethetext
Privacy&Terms

SubmitYourComment

EnterpriseDevelopmentUpdate
Don'tmissanarticle.Subscribetoournewsletterbelow.
EnterEmailAddress

MostPopularDeveloperStories
Today
ThisWeek
AllTime
1UsingJDBCwithMySQL,GettingStarted
2AnIntroductiontoJavaAnnotations
3MIDPProgrammingwithJ2ME
4AnIntroductiontoJSPStandardTemplateLibrary(JSTL)
5DebuggingaJavaProgramwithEclipse
1UsingJDBCwithMySQL,GettingStarted
2AnIntroductiontoJavaAnnotations
3AnIntroductiontoJSPStandardTemplateLibrary(JSTL)
4MIDPProgrammingwithJ2ME
5DebuggingaJavaProgramwithEclipse
1UsingJDBCwithMySQL,GettingStarted
2AnIntroductiontoJavaAnnotations
3AnIntroductiontoJSPStandardTemplateLibrary(JSTL)
4MIDPProgrammingwithJ2ME
5DebuggingaJavaProgramwithEclipse

SIGNUP

MostCommentedOn
ThisWeek
ThisMonth
AllTime
110ExperimentalPHPProjectsPushingthe
Envelope
2Day1:LearningtheBasicsofPL/SQL
3C#Tip:PlacingYourC#Applicationinthe
SystemTray
4LogicalVersusPhysicalDatabaseModeling
5IsUbuntuContributingasMuchasItShouldto
FreeSoftwareProjects?
1Day1:LearningtheBasicsofPL/SQL
2The5DeveloperCertificationsYou'llWishYou
Hadin2015
310ExperimentalPHPProjectsPushingthe
Envelope
4AnIntroductiontoStruts
5InsideFacebook'sOpenSourceInfrastructure
1CreatingUseCaseDiagrams
2Day1:LearningtheBasicsofPL/SQL
3C#Tip:PlacingYourC#Applicationinthe
SystemTray
4UsingASP.NETToSendEmail
5UsingJDBCwithMySQL,GettingStarted

TopWhitePapersandWebcasts
TheChallengesand
RewardsofBigData
Asallsortsofdatabecomes
availableforstorage,analysisand
retrievalsocalled'BigData'
therearepotentiallyhugebenefits,
butequallyhugechallenges...

TurningBigDatainto
UsefulInformation
Theagileorganizationneeds
knowledgetoacton,quicklyand
effectively.Thoughmany
organizationsareclamouringfor
"BigData",notnearlyasmany
knowwhattodowithit...

TheChallengesofCloud
Integration
Cloudbasedintegrationsolutions
canbeconfusing.Addingtothe
confusionarethemultiplewaysIT
departmentscandeliversuch
integration...

Sitemap|ContactUs

PropertyofQuinstreetEnterprise.
TermsofService |Licensing&Reprints|AboutUs|PrivacyPolicy|Advertise
Copyright2016QuinStreetInc.AllRightsReserved.

Thanksforyourregistration,followusonoursocialnetworkstokeepuptodate

Anda mungkin juga menyukai