Tải bản đầy đủ - 0 (trang)
Hack 89. Fun with Keyboard Lights

Hack 89. Fun with Keyboard Lights

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

























































privatebooleango;

publicvoidquit(){



go=false;

}

publicvoidrun(){



go=true;



//getatoolkit



Toolkittk=Toolkit.getDefaultToolkit(



//savetheoldkeystates



booleanold_num,old_caps,old_



old_num=tk.getLockingKeyState(KeyEven



old_caps=tk.getLockingKeyState(KeyEve



old_scroll=tk.getLockingKeyState(KeyE

































//setallkeystooff

tk.setLockingKeyState(KeyEvent.VK_NUM_L

tk.setLockingKeyState(KeyEvent.VK_CAPS_

tk.setLockingKeyState(KeyEvent.VK_SCROL



SpinnerThreadisaRunnableimplementation,meaningyoucan



launchitwithnewTHRead(newSpinnerThread()).start().Therun()

methodstartsaninfiniteloop,endingonlywhenthequit()

methodiscalled.Thefirstthingtonoticeisthatthecodesaves

theexistingstateofthebuttonssothatitcanrestorethem

later.IfyouhadCapsLockonyou'dprobablystillwantiton

oncethebusycursorleaves.Next,itsetsallofthekeystatesto

false.Thisputsthemintoaknownpositionsothatthe

animationlooksright:















intkey=-1;

booleanstate=false;

//loopthrough100times

intcounter=0;

while(go){

























//selecteachkeyevery3rdtime

if(counter%3==0){key=KeyEvent.VK_NUM_LOCK;}

if(counter%3==1){key=KeyEvent.VK_CAPS_LOCK;}

if(counter%3==2){key=KeyEvent.VK_SCROLL_LOCK;}

//flipthestate

state=tk.getLockingKeyState(key);

tk.setLockingKeyState(key,!state);

//sleepfor500msec

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

}catch(InterruptedExceptionex){}







}













//incrementcounter

counter++;



//restorethekeysettings

tk.setLockingKeyState(KeyEvent.VK_NUM_LOCK,old_num);

tk.setLockingKeyState(KeyEvent.VK_CAPS_LOCK,old_caps);

tk.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK,old_scrol



Nextcomestheloop,whichflipsonekeyeachtimethroughthe

loop,cyclingbetweenthethreekeys.Thisiswhatproducesthe

actualanimation.Oncetheloopisfinished,thekeyboardstates

arerestored.

Revisitingthishack(Ifirstwroteitforablogon

http://www.java.net),Ihavebeenlookingforotherinteresting

ideas.Onepoppedoutatmeasbeingtrulyannoying,soI

chosetoincludeithere.TheclassinExample12-3flashesthe

ScrollLockkeyoneverykeystroke.Thus,yourcomputerwill

keepintimewithyourtyping.Isthisthefutureofhumancomputerevolution,orjustplainannoying?

Thekey,sotospeak,ofthishackisonceagaintheToolkit

object.Itcontainsaveryinterestingmethod,addAWTEventListener(



),thatletsyouaddalistenerforeveryeventdispatched

throughouttheJVM.Thisisequivalenttoputtingalisteneron

eachcomponentinyourentireprogram.Thismethodismainly

intendedfordebuggersandtestingtools,butI'veuseditto

listenforapplication-widekeystrokeevents.



Example12-3.ScrollLockkeepingupwithtyping













publicclassKeyboardFlasherimplementsAWTEventListene



publicstaticvoidmain(String[]args){



Toolkittk=Toolkit.getDefaultToolkit();



KeyboardFlasherflasher=newKeyboardFlasher()



tk.addAWTEventListener(flasher,AWTEvent.KEY_EV



























}



JFrameframe=newJFrame("Hack#89:Funwith

JTextFieldtf=newJTextField("thisissomete

frame.getContentPane().add(tf);

frame.pack();

frame.setVisible(true);



KeyboardFlasherimplementstheAWTEventListenerinterfaceandthe



mainmethodaddsanewflashertothetoolkitasalistener.

tk.addAWTEventListener'ssecondargument,AWTEvent.KEY_EVENT_MASK,

indicatesthatthelistenershouldreceivekeyeventsonly.IfI

wantedtheprogramtoalsolookformouseclicks,thenIwould

doabitwiseOR(|)ofKEY_EVENT_MASKwithMOUSE_EVENT_MASK.Finally,

themain()methodcreatesatextfieldinaframetotestout

generatingkeyboardevents:









publicvoideventDispatched(AWTEventevt){



if(evtinstanceofKeyEvent){





KeyEventkevt=(KeyEvent)evt;



































}















}



if(kevt.getID()==KeyEvent.KEY_PRESSED



System.out.println("keyevent:



if(kevt.getKeyCode()!=KeyEven



flipScrollLock();



}

}















publicvoidflipScrollLock(){



Toolkittk=Toolkit.getDefaultToolkit();



booleanstate=tk.getLockingKeyState(KeyEvent.



tk.setLockingKeyState(KeyEvent.VK_SCROLL_LOCK,!

}



AsanimplementationofAWTEventListener,KeyboardFlasherhasone

requiredmethodonly,eventdispatched().Thisreceivesallevents

generatedinthesystem.Thisimplementationfirstchecksthat

theeventisindeedakeyboardevent,andthenchecksifitisa

KEY_PRESSEDevent.Thiswilldistinguishbetweenthekeygoing

downandthekeygoingup.Then,themethodcheckstomake

surethatthekeypressedisn'ttheScrollLockkey.



IfIdidn'taddthischeck,thecodewouldgointoaninfiniteloop,as

eachflipoftheScrollLockkeywouldgenerateaneweventandtrigger

anewflip.



FinallycomesflipScrollLock(),whichdoesexactlywhatit

suggests:flipsthestateoftheScrollLockkeyeachtimeitis

called.Inotherwords,ittakestwostrokestocompleteacycle.

Forafastereffect,youcouldmakethelightturnonwiththe

downwardstrokeandthenoffagainwiththeupwardstroke.



YouwouldjustneedtocallflipScrollLock()twice,onceforeach

event.

setLockingKeyState()isoneofthosenut-balllittlefunctionsthat



seemstohavenopurpose,butitsureletsushavesomefun.

Whatotherusescanyouthinkup?Anewemailalert?Athreebarsoundmeter?AWi-Fistrengthindicator?



Hack90.CreateDemonstrationswiththeRobot

Class



UsetheRobotclasstocontrolthemousecursorand

createinteractivesoftwarefeatures.

OneofthecoolestthingsaboutSwingisthatyoucanoftenuse

aclassforsomethingcompletelydifferentthanwhatitwas

originallyintended.Thejava.awt.Robotclass,forexample,can

movethemousecursorprogrammatically.Thisfeaturewas

originallyintendedforusebyautomatedtestingtools(hence

thenameRobot),butI'vefounditveryusefultodemonstrate

softwarefeaturesbymovingthemousecursorthroughthe

sameactionsastheuser.Insteadofjustdescribingsomething

inahelpfile,youcanactuallyshowtheuserwhattodoandthis

hackexplainshow.



12.4.1.I,Robot

Tocreateamouseanimation,youneedthreethings:

1. Theabilitytomovethecursor

2. Thestartandendpointsoftheanimation

3. Awaytosmoothlyinterpolatethecursorposition

Thejava.awt.Robotclasshasavarietyofmethodsforcapturing

programstateandcontrollingtheuserinterface,including

Robot.mouseMove(),whichallowsyoutomovethemousecursor

programmatically.



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);



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

Hack 89. Fun with Keyboard Lights

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

×