Tải bản đầy đủ - 0 (trang)
Hack 90. Create Demonstrations with the Robot Class

Hack 90. Create Demonstrations with the Robot Class

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

ThefollowingcodeistheimplementationofamethodmoveMouse(

),whichtakesthreearguments:astartingcomponent,an

endingcomponent,andadurationfortheanimation(in

milliseconds).Becausemostdemonstrationsinvolveshowing

theuseraparticularcomponent,theeasiestpointstouseare

thecentersofstartandendcomponents.Themousewill

smoothlymovefromthecenterofthestartingcomponentto

thecenteroftheendingone.Wenormallythinkofcomponents

asbeingpositionedrelativetotheirparents,butsincetheRobot

classusesabsolutemousepositions,you'llneedtoconvertthe

componentstotheirscreenlocations:















publicvoidmoveMouse(JComponentstart,JComponentend,



finalintduration)throwsException{



finalRobotrobot=newRobot();



//getmiddleofstart



finalPointstart_coords=start.getLocationOnS



start_coords.translate(start.getWidth()/2,































//getmiddleofend

finalPointend_coords=end.getLocationOnScree

end_coords.translate(end.getWidth()/2,

































end.getHeight()/2);

//createinterpolationpointandoffsets

intsteps=duration/50;

//Pointcurrent=newPoint(start_coords);

intdistx=(end_coords.x-start_coords.x);

intdisty=(end_coords.y-start_coords.y);



























//movethemouseover10steps

for(inti=1;i<=steps;i++){



intx=start_coords.x+i*distx/steps;



inty=start_coords.y+i*disty/steps;



robot.mouseMove(x,y);



start.getHeight()/2);





























}



}



try{Thread.currentThread().sleep(50);

}catch(Exceptionex){}



ThiscodecreatesanewRobotandcalculatesthecenterpositions

ofthestartandendcomponentsusingscreencoordinates.steps

isthenumberofframesrequiredtofillthespecifiedduration.

Sinceeachframewillbe1/20ofasecondlong,thenumberof

framesisthetotaldurationdividedby50ms.distxanddistyare

thedistancesbetweenthetwocomponentsinthehorizontal

andverticaldirections.Withthesevaluesinhand,itisasimple

mattertointerpolateanewpositionforeachframeandthen

movethemousecursorthere.

Totestthesystem,you'llneedsomesortofademonstration

program.ThecodeinExample12-4createsafakefilebrowser

withalistofdirectories,alistoffiles,andatoolbarwiththree

buttons:Info,NewDir,andDelete.YoucanseethisinFigure

12-2.



Figure12-2.Sampleprogramtodemonstrate

mouseautomation



Example10-4.Asimpledemonstrationforthe

powerofRobot











publicclassAutoMouseHackimplementsActionListener{



publicJButtoninfo,new_dir,delete;



publicvoidcreateDemo(){



JFrameframe=newJFrame("FileFlipper");























String[]dirs={".","..","build","docs","lib",

String[]files={"build.xml","readme.txt"};

JListdir_list=newJList(dirs);

JListfiles_list=newJList(files);



















JSplitPanesplit=newJSplitPane(



JSplitPane.HORIZONTAL_SPLIT,



dir_list,files_list);



















info=newJButton("Info");

new_dir=newJButton("NewDir");

delete=newJButton("Delete");



























JPaneltoolbar=newJPanel();

toolbar.setLayout(newFlowLayout());

toolbar.add(info);

toolbar.add(new_dir);

toolbar.add(delete);



















frame.getContentPane().setLayout(newBorderLayo

frame.getContentPane().add("North",toolbar);

frame.getContentPane().add("Center",split);















}



frame.pack();

frame.show();



ThedemonstrationprogramalsocontainsaHelpscreen(shown

inFigure12-3).



Figure12-3.Helptext



ThisisanHTMLpanewiththehelptextinit,plusCloseand

ShowMebuttons.ClickingShowMewilltakecontrolofthe

mousecursorandshowtheanimation.NotethattheJEditorPane

switchestoHTMLmodeautomaticallyifyouputinacontent

typeoftext/htmlandstartthebodytextwith:















JButtonshowme;

publicvoidcreateHelp()throwsIOException{



JFrameframe=newJFrame("Help");



JButtonclose=newJButton("Close");



showme=newJButton("ShowMe");



showme.addActionListener(this);







































JEditorPanehtml=newJEditorPane("text/html",



""+



"

Usethetoolbarbuttonstointeract



"

Infodisplaypropertiesoft



"

NewDircreateanewdirecto



"

Deletedeletethecurrently



clickShowMebelowto

);























frame.getContentPane().setLayout(newBorderLayo

frame.getContentPane().add("North",close);

frame.getContentPane().add("Center",html);

frame.getContentPane().add("South",showme);



















frame.pack();

frame.setLocation(400,50);

frame.setVisible(true);



























}

publicstaticvoidmain(String[]args)throwsE



AutoMouseHackhack=newAutoMouseHack(



hack.createDemo();



hack.createHelp();











}



Withademonstrationprogramandsomehelptext,nowyou

cancreatetheactualanimation.ThemoveMouse()functionmoves

themousecursorfromonelocationtoanotheroveracertain

amountoftime.Ifyoumakethecursorstartandendonthe

samecomponent,thenitwillactasatimedelay,makingthe

cursorappeartopauseoverthatcomponent:

















publicvoidactionPerformed(ActionEventevt){



try{





moveMouse(showme,info,2000);





moveMouse(info,info,1000);





moveMouse(info,new_dir,1000);





moveMouse(new_dir,new_dir,1000);





moveMouse(new_dir,delete,1000);





















moveMouse(delete,delete,1000);

moveMouse(delete,showme,500);



















}



}catch(Exceptionex){



System.out.println(""+ex);

}



Theeventhandlermovesthecursorfromtheshowmebutton,

whichiswherethecursorwillalreadybeanyway,totheinfo

toolbarbuttonoveraperiodoftwoseconds.Afterthat,the

cursorwillhopfrombuttontobuttontakingonesecondto

movewithaonesecondpauseovereachbutton.Finally,the

cursorrushesbacktotheshowmebuttoninahalf-second.Itis

importanttoreturnthecursortoitsstartingpositionsothatthe

userwon'thavetohuntforitaftertheanimationiscomplete.

It'sbesttoalwaysreturnthingstothestateyoufoundthem.



Hack91.CheckYourMailwithSwing



Addemailcheckingtoyourapplicationwithjustafew

methodcalls.

Asemailbecomesabiggerpartofourdailylives,Ihaveseenit

creepintomoreandmoreplaces.Myemailprogramalertsme

whenthereisnewmail.Icancheckmyemailviathephone.I

logintomywebmailfromanInternetcafe.Emailis

everywhere,sowhyshouldn'titbeinyourSwingapplication?

Thishackshowshowtoembedinyourapplicationanemail

checkerthatshowsthecurrentnumberofunreadmessages

andcanlaunchtheuser'semailapplication.

Dealingwithemailserverscanbeacomplicatedandtricky

business.Tohelpaddresstheseissues,Suncreatedthe

JavaMailAPI,whichisasetofclassesdefiningavendor-neutral

interfaceforaccessingemailservers.



Sun'ssampleimplementationprovidesIMAPsupport,whichiswhatI

willdemonstratehere.Ifyouhaveanotherkindofemailserver,suchas

Exchange,youcouldinstallyourownserviceprovideranduseitthe

sameway.



Thecodeinthishackneedstodotwothings.First,itmustopen

aconnectiontotheemailserverperiodicallyandcheckfornew

mail.Second,itmustlaunchtheuser'semailprogramona

double-click.Ihaveencapsulatedtheemailcheckingand

launchingcodeintoseparateclasses,makingitveryeasyto

addtoanexistingprogram.



TheEmailCheckerclass,showninExample12-5,isasimple

RunnableimplementationthatreceivesaJLabeltoitsconstructor.

Therunloopwillsleepforacertainamountoftime(oneminute

inthiscase)thencallcheckEmail().Everytimethereisnewmail,

itwillsetthetextofthelabeltosomethinglike"YouhaveNnew

messages."



Example12-5.Checkingfornewmessages











importjava.util.Properties;

importjavax.swing.JLabel;

importjavax.swing.SwingUtilities;

importjavax.mail.*;















publicclassEmailCheckerimplementsRunnable{



privateJLabellabel;



publicEmailChecker(JLabellabel){





this.label=label;



}











































publicvoidrun(){



while(true){







try{





checkEmail();





Thread.currentThread().sleep(10





}catch(Exceptionex){





System.out.println("exception:





ex.printStackTrace();





























}





}



}



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

Hack 90. Create Demonstrations with the Robot Class

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

×