Tải bản đầy đủ - 0 (trang)
Hack 11. Create Menus with Drop Shadows

Hack 11. Create Menus with Drop Shadows

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

onlydoestwothingsspecial:addsacustombordertothepop

up'sparentpanelandsetsthepaneltobetransparent.



Example1-25.Extendingthepop-upmenu'sUI























publicclassCustomPopupMenuUIextendsBasicPopupMenuUI



publicstaticComponentUIcreateUI(JComponentc





returnnewCustomPopupMenuUI();



}



publicPopupgetPopup(JPopupMenupopup,intx,





Popuppp=super.getPopup(popup,x,y);





JPanelpanel=(JPanel)popup.getParent(





panel.setBorder(newShadowBorder(3,3));





panel.setOpaque(false);





returnpp;











}



}



ThegetPopup()methodgeneratestheactualmenuobjectinthe

superclass.Thisversiongrabsthepopup'sparentaJPaneland

addsthecustomShadowBorderwithoffsetsof3pixels,both

horizontallyandvertically.ItalsocallssetOpaque(false).Thistells

thecomponentthatitdoesnothavetocompletelyfillits

boundariesandthattheparentcomponentmayshowthrough.

Formostcomponents,thisturnsoffitsbackground,whichis

thedesiredeffecthere.

Withthecustompop-upclassdone,it'stimetocreatethe

border.ShadowBorder,showninExample1-26,isasubclassof

AbstractBorder,whichhandlesallofthemessydetailsofborder

managementandletsthedevelopergetdowntotheactual

drawingcodeprettyquickly.



Example1-26.Addingashadowedborder

















classShadowBorderextendsAbstractBorder{



intxoff,yoff;



Insetsinsets;



publicShadowBorder(intx,inty){





this.xoff=x;





this.yoff=y;





insets=newInsets(0,0,xoff,yoff);























}

publicInsetsgetBorderInsets(Componentc){



returninsets;

}























}





















}



publicvoidpaintBorder(Componentcomp,Graphic

intx,inty,intwidth,intheight){

g.setColor(Color.black);

g.translate(x,y);

//drawrightside

g.fillRect(width-xoff,yoff,xoff,height-yoff)

//drawbottomside

g.fillRect(xoff,height-yoff,width-xoff,yoff)

g.translate(-x,-y);



TheShadowBorderconstructortakesx-andy-offsetsandcreatesan

Insetsobject.Theseinsetshavetobereturnedbythe

getBorderInsets()methodinorderforothercomponentstosize

themselvesappropriately.Becausetheinsetsclassusesa0for

thefirsttwoarguments,theextraspacewillbeontherightand

bottomonly,notthetopandleft.Thiswillcreateanoffset

shadowinthelower-rightdirection,similartomostnative



operatingsystemdropshadows.

Theactualpaintingcodeisverysimple:setthecolortoblack,

translatethegraphicsorigintoberelativetothexandypassed

in,drawtheshadow,andtranslateback.Theshadowis

composedoftwofilled-inrectangles,oneonthebottomofthe

componentandoneonitsrightside.Notethatthedrawing

beginsoffsetslightly.Therightsidestartsatyoffinsteadof0,

andthebottomsidestartsatxoff.Theseadjustmentswill

createatinysquareofemptyspaceinthelowerleftandupper

right.Thosesquareswillallowthebackgroundtoshowthrough.

Becausethebackgroundpanelwasalreadyturnedoffinthe

CustomPopupMenuUI'sgetPopup()method,thiswilllettheother

componentsunderneaththemenushinethrough.Thedrop

shadoweffectiscomplete.

ThecodeinExample1-27installstheCustomPopupMenuUIintothe

UIManager.Thiswillensurethatallmenusthroughoutthe

programusethecustommenu.Finally,thetestprogram

createsasamplesetofmenusandsomedummycomponents

inthemainframe.ThefinishedprogramlookslikeFigure1-29.



Example1-27.Puttingthecustomcomboboxinto

action

















publicclassMenuTest{



publicstaticvoidmain(String[]args)throwsE





UIManager.put("PopupMenuUI","CustomPopu





JFrameframe=newJFrame();





JMenuBarmb=newJMenuBar();





frame.setJMenuBar(mb);



























JMenumenu=newJMenu("File");

mb.add(menu);

menu.add(newJMenuItem("Open"));

















































































































}



}



menu.add(newJMenuItem("Save"));

menu.add(newJMenuItem("Close"));

menu.add(newJMenuItem("Exit"));

menu=newJMenu("Edit");

mb.add(menu);

menu.add(newJMenuItem("Cut"));

menu.add(newJMenuItem("Copy"));

menu.add(newJMenuItem("Paste"));

menu.add(newJMenuItem("PasteSpecial..

frame.getContentPane().setLayout(newBo

frame.getContentPane().add("North",new

frame.getContentPane().add("Center",new

frame.getContentPane().add("South",new

frame.pack();

frame.setSize(200,150);

frame.show();



Figure1-29.Menuwithadropshadow



Hack12.AddTranslucencetoMenus



InthishackIwillshowyouhowtoaddtruetranslucency

toyourmenuswithonlyaslightmodificationtoyour

program.

Computerinterfacesareprettysophisticatedthesedays.Years

ago,weconsideredourselvesluckytosimplyhavemenubars

atall;now,weneedmenuswithsophisticatedeffectslike

animation,shadows,andtranslucency.

You'vealreadyseenhowtoachievevisualeffectsbyoverriding

thepaint()methodofaparentcomponentandthenrendering

thechildrenintoabuffer[Hack#9].Itwouldbenicetodothe

samethinghere,butthere'sjustonesmallproblem.Overriding

thepaint()methodoftheJMenuwouldn'tdoanygoodbecause

theJMenudoesn'tdrawwhatwethinkofasamenualistofmenu

itemsthatpopupwhenyouclickonthemenu'stitle.TheJMenu

actuallyonlydrawsthetitleatthetopofamenu.Therestof

themenuisdrawnbyaJPopupMenucreatedasamemberofthe

JMenu.Unfortunatelythismemberismarkedprivate,which

meansyoucan'tsubstituteyourownJPopupMenusubclassforthe

standardversion.

Fortunatelythereisawayout.LikeallSwingcomponents,the

menucomponentsdelegatetheiractualdrawingtoaseparate

setofLookandFeelclassesinthejavax.swing.plafpackage.If

youoverridetherightplafclassesforthemenuitemsandpopupmenu,thenyoushouldbeabletocreatethedesired

translucenteffect.Itjusttakesalittlesubclassing.



1.13.1.MaketheCustomMenuItem



AllMenuItemsareimplementedbysomeformofthe

javax.swing.plaf.MenuItemUIclass.WhencreatingcustomUI

classes,itisalwaysbesttostartbysubclassingsomethingin

thejavax.swing.plaf.basicpackage(inthiscase,BasicMenuItemUI)

becauseithandlesmostoftheheavyliftingforyou,asshown

inExample1-28.



Example1-28.ExtendingthebasicUI











publicclassCustomMenuItemUIextendsBasicMenuItemUI{



publicstaticComponentUIcreateUI(JComponentc





returnnewCustomMenuItemUI();



}



















publicvoidpaint(Graphicsg,JComponentcomp)



//painttothebufferedimage



BufferedImagebufimg=newBufferedImag

































































































}



Graphics2Dg2=bufimg.createGraphics()

//restoretheforegroundcolorincase

g2.setColor(g.getColor());

super.paint(g2,comp);

//doanalphacomposite

Graphics2Dgx=(Graphics2D)g;

gx.setComposite(AlphaComposite.getInsta



AlphaComposite.SRC_OVER,0.8f));

gx.drawImage(bufimg,0,0,null);







}



comp.getWidth(),

comp.getHeight(),

BufferedImage.TYPE_INT_ARGB);



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

Hack 11. Create Menus with Drop Shadows

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

×