Tải bản đầy đủ - 0 (trang)
Hack 52. Use HTML and CSS in Text Components

Hack 52. Use HTML and CSS in Text Components

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

Figure7-11.Italictext



Youdon'tneedtomatchthewithantagatthe

end.Swing'sHTMLparserisprettytolerantofmalformedHTML,

soforsimplethingsyoucanjusttypewhateverisshortest.The

modecanonlybesetonce,soifyouputplaintextintothe

componentfirstandthenHTMLlater,itwillstillbeinplaintext

mode.Youshouldnotethatslowercomputerswillexhibita

noticeabledelaythefirsttimeacomponentisshownwith

HTML.ThisisbecauseSwinghastoloadupallofthe

javax.swing.text.htmlclasses;however,theyarecachedforany

furtherinstances.



Toavoidthisinitialdelay,youcouldloadahiddencomponentina

separatethreadduringprogramstartup.



HTMLcanbeusedasashortcutfortexteffectsthatwouldbe

cumbersomeorimpossiblewithstandardFontobjects.For

example,Fontdoesn'tprovideawaytodrawunderlinedtext,

butwithHTMLyoucandothis:

JLabell1=newJLabel("underlined");



ThisproducesthetextseeninFigure7-12.



Figure7-12.Underlinedtext



HTMLalsoletsyougetmulti-linedtextandmixedfonts:

JButtonb2=newJButton("mybutton");



ThisproducesthebuttonseeninFigure7-13.



Figure7-13.Mixedstyles



Youcanevenaddlinebreaktags:

JLabell2=newJLabel("mymulti-
linetext");



Usingthis,yougetthebuttonseeninFigure7-14.



Figure7-14.Multi-linedtext



YoucanuseHTMLinmorethanjustlabelsandbuttons.

JCheckBox,JRadioButton,andevenJComboBoxsupportit.Hereisan

exampleofeach:















JCheckBoxcb1=newJCheckBox("Therealth

JRadioButtonrb1=newJRadioButton(



"Evenbetter
String[]vals={"better",



"yetagain"};

JComboBoxcombo1=newJComboBox(vals);



ThiscreatesthecollectionofHTML-styledcomponentsseenin

Figure7-15.



Figure7-15.SomeotherHTMLcomponents



SwingsupportsmostfeaturesofbasicHTML:paragraphs,lists,

simpletables,andcolors.ItalsosupportsbasicCSS,whichcan

giveyougreatercontroloverborders,padding,andothervisual

attributes.Thisnextexamplecreatesaheaderfollowedbylist

itemsoflargecoloredtextsurroundedbyaborder.Sincethere

issomuchmarkup,IputitintoaStringBufferfirst:





StringBuffersb=newStringBuffer();





sb.append("");



sb.append("li{font-style:italic;font-size:30pt;}"



sb.append("li{font-family:serif;color:#ff5555;}")



sb.append("ul{border-width:4px;border-style:solid;









border-color:#ff0000;}");

sb.append("ul{background-color:#ffeeee;}");



sb.append("");



sb.append("

H3Header

");



sb.append("
  • largeserifedtext
  • aslisti



    sb.append("");





    JLabell3=newJLabel(sb.toString());



    ThisproducesthelabelseeninFigure7-16.



    Figure7-16.Bordersandlists



    ThereisnodefinitivelistofeveryCSSlayoutfeaturethe

    HTMLEditorKitsupports,butyoucangetagoodoverviewinthe

    JavaDocforthejavax.swing.text.html.CSSclass.

    CSSalsogivesyoutheabilitytodefineastyleandreuseitwith

    multiplecomponents,puttingyouonestepclosertothekindof

    separationofcontentandstylethatwetakeforgrantedonthe

    Web.Inthisexample,bothlabelssharethesameCSS



    declaration.Ifyouchangethedeclaration,itwouldchangeboth

    labels.Thisdeclarationcouldevenbestoredinapropertiesfile,

    lettingnon-programmersaffectthelookofyourapplication:

















    StringBuffercss=newStringBuffer();

    css.append("");

    css.append("body{color:#4444ff;font-weight:normal;

    css.append("");

    JLabell4=newJLabel(css+"Cartman");

    JLabell5=newJLabel(css+"Stan");



    ThisproducesthelabelsseeninFigure7-17.



    Figure7-17.SharedCSSstyles



    PuttingHTMLinSwingcomponentsisalittle-knownfeaturethat

    packsabigpunch.Youcanuseittoquicklycreatelayout

    effectsthatarecumbersomeorimpossibletodowithtraditional

    text.



    Hack53.UseGlobalAnti-AliasedFonts



    ThinkSwingappsalwayslookuglybecauseofthe

    chunkyfonts?Finally,youcandosomethingaboutit!

    Java1.2introducedJava2D,completewiththeabilitytodraw

    anti-aliasedtext.Unfortunately,anti-aliasingisoffbydefault

    andturningitonrequiresaprogrammaticchangeoneachUI

    component.Thishackshowshowtoturnonanti-aliasingforan

    entireframewithoutcustomizingeachcomponent.Italso

    introducesaspecialrepaintmanagerthatisthekeytoseveral

    otherhacksinthisbook,suchasthepartialtranslucentmenus

    [Hack#12].



    7.7.1.TheProblem

    Toturnonanti-aliasing,yousimplyneedtosetarendering

    hint:









    Graphics2Dg2=(Graphics2D)g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,







    RenderingHints.VALUE_ANTIALIAS_



    Unfortunately,theGraphicsobjectisnotverylong-lived.Thereis

    noglobalplacetosetahintbecausethere'sanewGraphics

    objectforeveryrepaint().Anypropertyyousetwouldbegone

    bythenextpaintcall.Theusualworkaroundistosubclassthe

    componentyouwanttoanti-aliasandoverridethepaint()

    method:





    classAAButtonextendsJButton{





    publicvoidpaint(Graphicsg){







    Graphics2Dg2=(Graphics2D)g;







    g2.setRenderingHint(RenderingHints.KEY_











    RenderingHints.VALUE_AN

    super.paint(g2);





    }



    }



    Thiswillwork,butitmeansyouhavetocreateacustom

    subclassforeverycomponentinyourapplication.Notavery

    appealingsolution.

    MacOSXprovidesanti-aliasedrenderingthroughasystem

    property,butthisonlyworksbecauseApplethoughtfullyadded

    ittotheirJVM.Developersonotherplatformsareleftout.Java

    5.0providesastandardsystempropertyforanti-aliasing,but

    thatdoesn'thelpthemillionsof1.3and1.4JVMsoutthere.

    Anotheroptionwouldbetousesomeformofcodeinjectionto

    modifyeachpaintmethodatthebytecodelevel,butthis

    requiresanAOPtool,custombuildscripts,andotherthingsthat

    areprobablyoverkillforsuchasimplefeature.Therehastobe

    abetterwayandthereactuallyis.

    Along,longtimeago(inaresearchlabfar,faraway)Iworked

    onascalableUItoolkitforJavacalledSubArctic.Oneofitskey

    featureswasthatacomponentwouldpaintontoacanvas

    objectcalledaDrawablewhatwewouldcallaGraphicsobjectin

    Swing.ThisDrawablewouldbepassedfromparenttochildina

    recursivetreetraversal.Drawablescouldbehackedtodoallsorts

    ofcomplicatedthings,andsinceachildalwaysdrewonthe

    Drawablefromitsparent,theparentcouldmakeachange

    withoutthechildknowingaboutit.Thus,youcouldcreatea

    parentpanelthatrotatedallgraphicsby45degreesanda

    standardchildcomponent(likeabuttonorscrollbar)would



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

Hack 52. Use HTML and CSS in Text Components

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

×