Tải bản đầy đủ - 0 (trang)
Hack 34. Make a Draggable Window

Hack 34. Make a Draggable Window

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

publicvoidmouseReleased(MouseEvente){}

publicvoidmouseMoved(MouseEvente){}

publicvoidmouseDragged(MouseEvente){

frame.setLocation(newPoint(e.getX(),e.get

}

}



ThisclassimplementsMouseListenerandMouseMotionListenerwith

no-opsforallmethodsexceptmouseDragged(),whichmovesthe

frametothecurrentmouselocation.However,thisapproach

hastwoproblems.First,themousecoordinatesaregoingtobe

relativetothecomponent,ratherthanthescreen.Thus,aclick

ona50x50buttoninthebottomrightofthescreenmight

return(25,25)whenitshouldreallybemorelike(1000,700).

Theotherproblemisthatthecodemovestheoriginofthe

frametothemousecursor.Thiswouldlookstrangebecausethe

windowwouldimmediatelyjumpsothatitsupper-leftcorneris

rightunderthecursor.Theproperbehaviorisforthewindowto

stayinthesamepositionrelativetothecursorasthecursor

movesaround.

Thesolutiontothefirstproblem(gettingscreencoordinates

ratherthancomponentcoordinates)istoconvertmouse

coordinatestoabsolutescreencoordinates.Thefollowing

methoddoesjustthat(we'llusethisshortlyinmouseDragged()):



PointgetScreenLocation(MouseEvente){

Pointcursor=e.getPoint();

Pointtarget_location=this.target.getLocationOnS

returnnewPoint(



(int)(target_location.getX()+cursor.getX()),

(int)(target_location.getY()+cursor.getY()))

}



Solvingthesecondissue(keepingthewindowstaticrelativeto

themouse)requiressavinganinitialoffsetbetweenwindow

andcursor,andthenmaintainingthatoffsetthroughoutthe

drag.YoushouldaddanewmousePressed()implementationthat

savesthecurrentscreenlocationofthemousecursor

(start_drag)andthecurrentlocationofthewindow(start_loc).

Thedistancebetweenthetwopointscanbeusedtoforman

offset:



Pointstart_drag;

Pointstart_loc;

publicvoidmousePressed(MouseEvente){

this.start_drag=this.getScreenLocation(e);

this.start_loc=this.getFrame(this.target).getLocat

}



Next,thelistenershouldmaintaintheoffsetdifference

throughoutthedragoperationbycalculatinganewoffseteach

timethemousemoves.HereisthenewmouseDragged()method:



publicvoidmouseDragged(MouseEvente){

Pointcurrent=this.getScreenLocation(e);

Pointoffset=newPoint(

(int)current.getX()-(int)start_drag.getX(),

(int)current.getY()-(int)start_drag.getY())

JFrameframe=this.getFrame(target);

Pointnew_location=newPoint(

(int)(this.start_loc.getX()+offset.getX()),

(int)(this.start_loc.getY()+offset.getY()))

frame.setLocation(new_location);

}



Usingtheutilitymethod,itgetsthecurrentmousepositionin

screencoordinates,andthencalculatesthedistancebetween

thatpositionandwherethemousestarted.Finally,itaddsthis

offsettothestartinglocationforthewindowtosetthe

window'sfinallocation.

Everynowandthen,theeventqueuewilldropamouseevent.

Ifthecodewasaddingthedeltas(changeinposition)from

eachdragevent,theneventuallytheuserwouldstarttosee

errorsasaresultofthesedroppedevents.Becausethiscode

alwaysrecalculatesthewindowpositionrelativetothestartof

thedrag,theseerrorsdon'thaveaneffect.Plus,sinceSwing

sendsallmouseeventstoadraggedcomponentevenifthe

cursormovesoutsidetheboundsofthecomponentyoudon't

havetoworryabouttheuserdraggingofftheedgeofthe

windowandshuttingdownthewholeprocess.

Thismethodofwindowdragginghastwostrengths.First,since

theworkisdoneinalistener,youcanaddthislistenertoany

existingSwingcomponentwithoutsubclassing.Anyoldprogram

canbecomedraggable!Second,onlydragsontheattached

componentaffectthewindowyoucanmakethebackgroundof

thewindowdraggablewithoutaffectinganyoftheforeground

components(likethePlaybuttononanMP3player).

Totestoutthemouselistener,tryaddingittotheCalendar

hack[Hack#4].Changethemain()functionlikethis:

publicstaticvoidmain(String[]args){

JFrameframe=newJFrame();

CalendarHackch=newCalendarHack();

ch.setDate(newDate());

frame.getContentPane().add(ch);



frame.setUndecorated(true);

MoveMouseListenermml=newMoveMouseListener(ch,f

ch.addMouseListener(mml);

ch.addMouseMotionListener(mml);



frame.pack();

frame.setVisible(true);

}



Theonlyadditionsarethefourboldlinesinthemiddleofthe

method.Thefirstlineturnsoffthestandardwindow

decorations,andthesecondcreatestheMoveMouseListenerwith

referencestotheCalendarHackcomponentanditsframe.Thelast

twolinesaddthelistenersothatitreceivesallofthemouse

eventsbeforetheframeisshownonscreen.

ThefinalhacklookslikeFigure5-1,withthetitlebarand

windowcontrolshiddenandtheentirecomponentdraggable.



Figure5-1.Adraggablecalendar



Hack35.AddWindowsResizeIcons



TheWindowsresizeiconsaren'tbuiltintoJava.Here's

howtomakeyourown.

Windowshastwostandardiconstoletusersknowthattheycan

resizeawindow.Ican'ttellyouwhytherearetwoorhowto

decidebetweenthem,butIcantellyouhowtoreproduceboth

oftheminJava.Notethatthishackisconcernedwithpainting

theiconsaccuratelyitwillbeuptoyourcodetohandleevents

oncomponentsthatusetheseiconsandhandlethem

appropriately.



5.4.1.ATaleofTwoIcons

Firsttakealookatthetwoicons.Figure5-2showstheicon

usedbyWindowsExplorer,MSPaint,andotherapplications;

Figure5-3showstheiconusedbyWordandotherOffice

applications.



5.4.2.TheIconInterface

Theeasiestandmostflexiblewaytoimplementtheseiconsis

throughtheIconinterface.UsingIconallowsyoutochangean

icon'sappearanceeasilyifyouneedtomatchnewsystem

defaults.It'salsoaloteasiertoimplementtransparencywith

anIconthanbymakinganimagefromthecornericonusinga

screencaptureandeditingitinaprofessionalgraphics

applicationlikePhotoshop.



Figure5-2.TheWindowsExplorerresizeicon



Figure5-3.TheWindowsMSOfficeresizeicon



Iconisprettysimple,andithasonlythreemethods:



voidpaintIcon(Componentc,Graphicsg,intx,inty);

intgetIconWidth();

intgetIconHeight();



ThegetIconWidth()andgetIconHeight()methodsshouldbepretty



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

Hack 34. Make a Draggable Window

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

×