Tải bản đầy đủ - 0 (trang)
Hack 86. Make Quick Look and Feel Changes

Hack 86. Make Quick Look and Feel Changes

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

Itisimportanttosetthesepropertiesbeforeanycomponentsare

createdortheywon'tpickupthenewsettings.



Belowisthecodeforasimpleprogramthatshowsafew

componentsinaframe.Ithasabutton,label,andtextfield

alongthetopandatextareainascrollpaneinthemiddle.

Thereisalsoasimplefilemenuatthetop.Beforecreatingany

components,itsetstheforegroundandbackgroundcolorsfor

thebutton,label,textfield,andpaneltolightanddarkgreen:













publicstaticvoidmain(String[]args)throwsException



Colorbg=Color.green.brighter();



Colorfg=Color.green.darker();



UIManager.put("Button.background",bg);



UIManager.put("Button.foreground",fg);































UIManager.put("Label.background",bg);

UIManager.put("Label.foreground",fg);

UIManager.put("TextField.background",bg);

UIManager.put("TextField.foreground",fg);

UIManager.put("Panel.background",bg);

UIManager.put("Panel.foreground",fg);



































JTextAreajta=newJTextArea();

jta.setText("text\ntext\ntext\ntext\ntext\ntext



"\ntext\ntext\ntext\ntext\ntext");

JScrollPanescroll=newJScrollPane(jta);

JButtonbutton=newJButton("AButton");

JLabellabel=newJLabel("ALabel");

JTextFieldtext=newJTextField("ATextField")



















JMenuBarmb=newJMenuBar();

JMenufile=newJMenu("File");

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







































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

mb.add(file);

JFrameframe=newJFrame("CustomLaFDefaults"

JPaneltop=newJPanel();

top.setLayout(newBoxLayout(top,BoxLayout.X_AXI

top.add(button);

top.add(label);

top.add(text);























JPanelpanel=newJPanel();

panel.setLayout(newBorderLayout());

panel.add("North",top);

panel.add("Center",scroll);















frame.getContentPane().add(panel);

frame.setJMenuBar(mb);



















}



frame.pack();

frame.setSize(300,200);

frame.setVisible(true);



Whencompiled,thiswilllooklikeFigure11-11.

Swingprovidesover300propertiesthatdefinethecolorsand

fontsofeachstandardcomponent.Thisletsyoucustomize

almostanythinginyourprogram.Youcanevensetacolortobe

transparent,whichmaylookinterestingifyouhaveapattern

background.



Figure11-11.Asampleprogramwithgreen

components



11.9.2.TextComponents

Textcomponentshavefontsettingsinadditiontotheircolors.

Thisletsyousetacomponenttouseadifferentfontstyleor

size.Youcanevenloadacustomfontfromafile:











Fontfont=Font.createFont(Font.TRUETYPE_FONT,



newFileInputStream("dungeon.ttf"));

font=font.deriveFont(Font.BOLD,16f);

UIManager.put("Label.font",font);



ThiswouldlooklikeFigure11-12.



Figure11-12.Acustomfont



Mostcomponentsalsohavemarginsthataredefinedbyan

Insetsobject.Atextfieldwithlargeinsets:





UIManager.put("TextField.margin",newInsets(25,25,25,2



wouldlooklikeFigure11-13.



Figure11-13.AJTextFieldwithlargeinsets



Somecomponentsevenhaveborders.Menuitemshaveborders

buttheyareturnedoffbydefault.Youneedtosetanextra

booleantomakeanewbordershowup,asinFigure11-14.











Borderborder=BorderFactory.createEtchedBorder(



EtchedBorder.LOWERED);

UIManager.put("MenuItem.border",border);

UIManager.put("MenuItem.borderPainted",newBoolean(tru



Figure11-14.Menuitemswithetchedborders



11.9.3.UseSystemColors

TheUIManagerletsyouchangeanycolorinyourapplicationto

whateveryouwant.Now,whatifyouwantedtocreateatheme

thatmatchedthenativeoperatingsystemcloser?Youcould

hardcodesomecolorvaluesforeachOS,butmostwindowing

systemsalsolettheiruserscustomizetheircolors.Hardcoded

valueswouldn'ttakethosedynamiccolorsintoaccount.

Fortunately,AWTprovidesawayout:theSystemColorclass.

SystemColorisaspecialsubclassofColorthatprovidesaccessto



mostofthestandardcolorsettingsofanyoperatingsystem.It

alsohasthespecialabilitytoupdateitselfwheneverthe

underlyingsystemcolorchanges.Thismeansiftheuser

switcheshernativecolorsfromacontrolpanel,yourapplication

willautomaticallyupdateitselftoreflectthenewsettings.

Insteadofmethods,SystemColorhasabunchofconstantsthat

defineeachtypeofcolorfromactiveCaptionTexttowindowBorder.

Thedocumentationisminor,soyouwillneedtoplayaround

withdifferentsettingstogettheeffectyouarelookingfor:











Colorsysbg=SystemColor.control;

Colorsysfg=SystemColor.controlText;

UIManager.put("Button.background",sysbg);

UIManager.put("Button.foreground",sysfg);



Thiscodesetsthebackgroundandforegroundofeverybutton

tousethecontrolandcontrolTextfieldsofSystemColor.Withmy

computersettousetheDeserttheme,itlookslikeFigure1115.



Figure11-15.WindowwiththeDeserttheme



IfIchangemywindowthemetohigh-contrastblack,itlooks

likeFigure11-16.

UIManagerpropertiesgivedevelopersasimplewaytocustomize



thecolors,fonts,andbordersofalmostanySwingcomponent.

Asanenhancement,youcouldallowuserstocustomizethe

colorsthemselvesandstorethevaluesinapropertiesfile.



Figure11-16.Windowwiththehigh-contrast

blacktheme



Hack87.CreateanInverseBlack-and-White

Theme



Createacustomblack-and-whitethemeformonochrome

LCDdisplaysusingafewsimpleUIManagercalls.

TheUIManagerletsyousetsimpleresourcesforcolor,fonts,and

padding,butyoumayhavenoticedthatifyouwanttothemeall

ofthecomponents,youneedtosetpropertiesoneachone.

SinceSwinghasover300LookandFeelproperties,thiscould

becomeaproblem.Fortunately,thereisanotherwaytomake

globalchangeswithoutcreatinganentirecustomL&F.Metal,

thestandardcross-platformL&FthatcomeswithSwing,can

usethemes.ThishackdemonstrateshowtocreateaMetal

themethatforcesthecomponentstouseonlyblackandwhite.

SwingletsyouswitchbetweendifferentLookandFeels.Youcan

useanativeLookandFeel(suchastheonethatcomeswith

MacOSX)orathirdpartyLookandFeelifyouhavethem

installed.SwingalsocomeswithastandardL&FcalledMetal.

MetalisbuiltintotheJREandisalwaysavailable,makingitthe

idealL&Ftocustomize.

LikeallL&Fs,Metalhasmany,manyclassesthatyoucan

subclasstomakechanges.However,italsocomeswithan

interfacecalledMetalTheme.IfyouimplementMetalTheme,thenyou

cancustomizemostofMetalwithoutdiggingintothedetails.

MostofthecolorsinMetalcanbeset,infact,withjustsix

values.Metalmakesiteveneasierbyprovidingadefault

implementationcalled,unsurprisingly,DefaultMetalThemethatyou

canuseasastartingpoint.



11.10.1.ABlack-and-WhiteTheme

AMetalthemeisdefinedbyaseriesofcolorsandfonts.The

mostimportantonesarethethreeprimaryandthreesecondary

colors.Thesedefinethestandardsetofcolorsusedforevery

widgetonscreen.Certaincomponentshaveadditionalcolors,

likethetextselection,butalmosteverythingisbasedonthese

six.Example11-9isathemethatusesonlywhiteandblack.It

isusefulforembeddeddevicesthatcan'taffordthehardwareor

memoryrequirementsofacolordisplay.



Example11-9.Ablack-and-whiteMetaltheme



importjavax.swing.plaf.metal.*;importjavax.swing.plaf.ColorU

publicclassInverseThemeextendsDefaultMetalTheme{



protectedColorUIResourcegetPrimary1(){





returnnewColorUIResource(255,255,255);



}



protectedColorUIResourcegetPrimary2(){





returnnewColorUIResource(0,0,0);



}



protectedColorUIResourcegetPrimary3(){





returnnewColorUIResource(255,255,255);



}























//componentborders

protectedColorUIResourcegetSecondary1(){



returnnewColorUIResource(0,0,0);

}

//selectedcomponents(buttondownstate)

protectedColorUIResourcegetSecondary2(){



returnnewColorUIResource(0,0,0);

}

//componentbackgrounds

protectedColorUIResourcegetSecondary3(){



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

Hack 86. Make Quick Look and Feel Changes

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

×