Tải bản đầy đủ - 0 (trang)
Hack 43. Create Custom Tool Tips

Hack 43. Create Custom Tool Tips

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













Graphics2Dg2=(Graphics2D)g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,



RenderingHints.VALUE_ANTIALIAS_ON);

g2.setColor(Color.white);

g2.fill(round);

















//drawthegrayborder

g2.setColor(Color.gray);

g2.setStroke(newBasicStroke(5));

g2.draw(round);

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,



RenderingHints.VALUE_ANTIALIAS_DEFAULT);





//drawthetext



Stringtext=this.getComponent().getToolTipText();



if(text!=null){

FontMetricsfm=g2.getFontMetrics();

inth=fm.getAscent();

g2.setColor(Color.black);





g2.drawString(text,10,(this.getHeight()+h)/





}



}



Thiscodecreatesaroundrectangleshapethatisthenreused

todrawthebackgroundandborder.Noticethatanti-aliasingis

turnedonfordrawingtheshape,butit'sturnedbacktothe

default(whichcouldbeonoroff)beforedrawingthetext.It

wouldlookstrangetohaveanti-aliasedtextiftherestofthe

interfacewasstillusingstandardaliasedtextusingthedefaultis

asaferidea.

Becausethistooltipneedsextraspacearoundthetexttodraw

theborder,youwillneedtomodifythetooltip'spreferredsize.

ThegetPreferredSize()methodhereaddsanextra20pixelsin

eachdirection:





publicDimensiongetPreferredSize(){





Dimensiondim=super.getPreferredSize();





returnnewDimension((int)dim.getWidth()+20,

(int)dim.getHeight()+20);



}



Thetooltiphasroundedcorners,butwiththecodeasitstands,

youwouldstillseethesliversofgraythatfilloutthe

component'srealcorners.Inordertohidethegrayandletthe

componentsbelowshinethrough,youneedtomakethetooltip

transparent.Youcandothisbysettingopaquetofalseinthetool

tip'sconstructor.Thetooltipcomponentisnotadirectchildof

theframethatcontainsthetooltip.Thereisanother

componentbetweenthetooltipandtheframethatwillbe

visibleevenifthetooltipistransparent.Youcanmakethis

extracomponenttransparentwithanadditionalsetOpaque(false)

callonthetooltip'sparentatthestartofthepaintComponent()

method:















publicCustomToolTip(){



super();



//makethetooltipnotfillinitsbackground



this.setOpaque(false);

}

publicvoidpaintComponent(Graphicsg){























//settheparenttonotbeopaque

Componentparent=this.getParent();

if(parent!=null){



if(parentinstanceofJComponent){





JComponentjparent=(JComponent)parent





if(jparent.isOpaque()){



jparent.setOpaque(false);



}

}









}

//…therestofthedrawingcode



6.4.1.InstalltheToolTip

Toinstallthecustomtooltip,youneedtooverridethe

createToolTip()methodofthecomponentyouwishtomodify.An

exampleusingacustomJButtonisshowninExample6-5.



Example6-5.Installingacustomtooltip







classCustomJButtonextendsJButton{



JToolTip_tooltip;























publicCustomJButton(){



_tooltip=newCustomToolTip();



_tooltip.setComponent(this);

}



















}



publicJToolTipcreateToolTip(){



return_tooltip;

}



BecausethetooltipisspecifiedbythecustomJButtonclass,all

youneedtodoiscreatesomecomponentsandsettheirtooltip

text.ThecodeinExample6-6createstwobuttonsandthree

labelsinaframe.Thebuttonshavecustomtooltipsthatwill

displaycompletewiththenowtransparentcornersontopofthe

restofthescreen,asshowninFigure6-6.



Figure6-6.Atooltipwithacustomborder



Example6-6.Testingoutcustomtooltips











publicclassToolTipsHack{





publicstaticvoidmain(String[]args){





JButtonbutton;







































JFrameframe=newJFrame("ToolTipsHa

BoxLayoutlayout=newBoxLayout(



frame.getContentPane(),



BoxLayout.Y_AXIS);

frame.getContentPane().setLayout(layou

































button=newCustomJButton();

button.setText("Open");

button.setToolTipText("Openanexisting

frame.getContentPane().add(button);

































button=newCustomJButton();

button.setText("Save");

button.setToolTipText("Savethecurrent

frame.getContentPane().add(button);















frame.getContentPane().add(newJLabel(





















frame.getContentPane().add(newJLabel(

frame.getContentPane().add(newJLabel(



















}







}



frame.pack();

frame.show();



Hack44.TurnDialogsintoFrame-Anchored

Sheets



OneofMacOSX'sbestideasisbindingthedialogtothe

windowitblocks.Thishackshowsyouhowtomimicthis

inSwing.

OneofmyfavoritefeaturesinMacOSXisthesheet.Thisisa

dialogboxreplacementthatslidesdownfromawindow's

titlebar.Figure6-7showsanexampleofasheetinApple's

Safariwebbrowser.



6.5.1.WhySheetsRock

Lookingatit,youmightthink,"what'sthebigdeal"or"howis

thisanydifferentthanaregulardialog?"Oh,it'sfarbetter:



Asheetisvisuallyanchoredtothewindowthatitblocks

Onplatformswheredialogshavetitlebarsandcloseboxes,

therelationshipbetweenadialogandthewindowitblocks

isnotnecessarilyintuitive.Onarelatedpoint….



Figure6-7.SheetinMacOSXSafaribrowser



Asheetdoesn'thaveaclosebox

Dialogcloseboxesareoneofthemosthatefulandstupid

conceptsinWindowsanditsmanyLinuximitators.What

doesthecloseboxmean?Cancel?Thedefaultoption?What

doesitmeanwhenthedialoghasmultipleoptionsofequal

plausibilityandthusnodefault?Perhapstheworstthing

aboutthecloseboxwasbackintheAWTerawhenJava

developerstoolazytoaddandwire-upanOKbuttontotheir

dialogsjustfigureduserscoulddismissthedialogwiththe

closebox.MacOS8and9dialogsdidn'thavecloseboxes,

sowhenaJavaapplicationbroughtupsuchadialog,the

applicationblockeditselfforever.Duh.Sheetsmeanhaving

toclickoneoftheprovidedbuttons,sotheuser'schoices

areunambiguous.



Asheetisusedtoblockonewindow

Thisisanobvioussideeffectofbeingvisuallytiedtoa

singlewindow,butthat'sprobablythemostcommoncase.

Asasideeffect,thisgivesgreaterprominencetodialogs

thatblockallwindowsforasingleapplication("Areyou

sureyouwanttoQuitandloseallunsavedchangesinall

documents?")anddialogsthatblockallapplications("Are

yousureyouwanttoShutDown?").



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

Hack 43. Create Custom Tool Tips

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

×