Tải bản đầy đủ - 0 (trang)
Hack 60. Changing Fonts Throughout Your Application

Hack 60. Changing Fonts Throughout Your Application

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

8.6.1.ChangingtheDefaultFonts

ThegoaloftheChangeAllFontsexampleistochangethedefault

fontofallSwingcomponents,bychangingalltheappropriate

keysitcanfindinUIDefaults.Itstartsbygettingafontname

fromthecommandlineandcreatinga12-pointplainFont

instance.

Next,itgetstheUIDefaultsobjectasaHashtableandgetsan

Enumerationofitskeys.Itwalkstheenumerationand,forevery

keyendingin.font,itusesput()toreplacethepreviousfont

withtheuser-selectedfont.

Finally,itcreatesasimpleGUIwithseveraltypicalJComponents

andshowstheminaJFrame.Thisshortexampleisshownin

Example8-7.



Example8-7.Changingdefaultfontsvia

UIDefaults

publicclassChangeAllFonts{







finalstaticString[]LIST_ITEMS=

{"JList","with","newFont"};

























publicstaticvoidmain(String[]args){



try{





//getuser'sfont





if(args.length<1){





System.out.println(







"Usage:ChangeAllFontsfont-nam





return;



}



StringfontName=args[0];



Fontfont=newFont(fontName,Font.PLAIN,12)



























//putthisfontinthedefaultstableforever

//uifontresourcekey

Hashtabledefaults=UIManager.getDefaults();

Enumerationkeys=defaults.keys();

while(keys.hasMoreElements()){



Objectkey=keys.nextElement();







if((keyinstanceofString)&&









(((String)key).endsWith(".font









System.out.println(key);









defaults.put(key,font);







}





}

































































//nowbringupaGUItoshowthisoff

JPanelpanel=newJPanel();

panel.setLayout(newBoxLayout(panel,BoxLayou

panel.add(newJLabel("JLabelwithfont"+fo

panel.add(newJTextField("JTextFieldwithfon

































JFrameframe=newJFrame("Changingde



frame.setDefaultCloseOperation(WindowC



frame.getContentPane().add(panel);



frame.pack();



frame.setVisible(true);

}catch(Exceptione){





fontName));

panel.add(newJButton("JButtonwithfont"+



fontName));

JListlist=newJList(LIST_ITEMS);

JScrollPanepane=



newJScrollPane(list,





ScrollPaneConstants.VERTICAL_SC





ScrollPaneConstants.HORIZONTAL_

panel.add(pane);









}







}





}



e.printStackTrace();



8.6.2.Fonts'R'Us

Torunthecode,youspecifythenameofyourdesiredfonton

thecommandlineastheonlyargumenttotheclass.Ifthefont

youwanttousehasoneormorespacesinitsname,you'll

needtoenclosethefontnameinquotes,asintheexample:

cadamson%javaChangeAllFonts"ComicSansMS"



ThisproducesaGUIwhosecomponentsallusethe12-point

plainComicSansMSfont,asseeninFigure8-5.



Figure8-5.ChangingdefaultfontsforSwing

widgets



Youshouldalsonotethestandardoutputwhenrunningthis



example,sincethecodeprintsoutevery.fontkeyitfinds.The

outputistoolongtolisthere,butthefirstfewitemslooklike

this:

Table8-1.

CheckBox.font



ToolBar.font



tree.font



ColorChooser.font



Viewport.font



ToggleButton.font



ProgressBar.font



Panel.font



RadioButtonMenuItem.font



TextArea.font



FormattedTextField.font



TheseareallJComponents,butthey'renotablylackingthe"J"thatstarts

thenameoftypicalSwingcomponents(tree.fontforJtree,TextArea.font

forJTextArea,etc.).



NowthatyouknowthekeysfortheUIDefaultstable,insteadof

blindlychangingallofthemtothesamefont,youcan

customizealookbyapplyingdifferentfontsordifferentsizes

andstylesofoneortwobasefontstodifferentwidgets.



Hack61.LoadNewFontsatRuntime



Whocareswhatfontsyourusershave?Bundlethefonts

youwantyourapplicationtouseandloadthosefonts

dynamically!

Usingfontswithanypredictabilityusedtobeanightmarein

Java.Forawhile,youcouldonlydependonhavingaccessto

oneserif,onesans-serif,andonemonospacedfont,andthe

constantsyou'dusetogetthosefontschangedbetweenJava

1.0and1.1.Fortunately,you'renowfreetouseanyfont

installedontheuser'smachineandloaditbyname.

Ofcourse,noteveryonehasthesamefonts.Evendifferent

installationsofthesameoperatingsystemwillhavedifferent

fontsavailable.IstillusesomeTrueTypefontsI'vebeentoting

frommachinetomachinefor15years,andit'sasafebetthat

veryfewotherpeoplewillhavethosesamefonts.

ThiswouldseemtolimityourSwingapplicationtousingonly

thefontsyouknowareinstalledwithanoperating

systemmaybeArialandTimesNewRomanonWindows,Lucida

GrandeandPalatinoonMacOSX,etc.Butit'snotso.Youcan

loadfontfilesatruntimeandmakethemavailabletoyourJava

application,evenifthefontisn'tinstalledontheuser's

machine.



8.7.1.TheWondersofcreateFont()

Usingdynamicallyloadedfontscomesdowntoasingle,critical,

oftenoverlookedAWTmethodintheFontclass:createFont().This

method,introducedinJava1.3,takestwoparameters:afont



format(asanint),whichtodatehasnolegalvalueotherthan

Font.TRUETYPE_FONT,andanInputStream.

ThisstreamistypicallyaFileInputStreamfroma.ttfTrueTypefile,

orsomeequivalent.Byequivalent,Imeantthatyoucould

presumablyputthefontonthenetworkandgetastreamfrom

aURLorputthefontfileinsidea.jar,finditalongtheclasspath

withClassLoader.getResourceAsStream(),andloadfromthat.



MacOSX'sfontsuitcasesaholdoverfromtheClassicMacOSaren't

supported.Yourfontsneedtobein.ttffiles.



FontLoadingDemo,showninExample8-8,offersastraightforward



applicationofthisfont-loadingtechnique.Ittakesthepathtoa

.ttffileasitscommand-lineargument,createsanInputStream,

andcreatesaFont.Itthenderivesaplain,32-pointinstanceof

thefont,andusesthattoputasampleJLabelinaJFrame.



Example8-8.Loadingfontsatruntime

publicclassFontLoadingDemo{























publicstaticvoidmain(String[]args){



try{





//getfontfrompathinargs[0]





if(args.length<1){







System.out.println(







"usage:FontLoadingDemopath-to







return;





}





Filef=newFile(args[0]);





FileInputStreamin=newFileInputStrea



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

Hack 60. Changing Fonts Throughout Your Application

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

×