Tải bản đầy đủ - 0 (trang)
Hack 59. Create a Color Eyedropper

Hack 59. Create a Color Eyedropper

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

Thefirststepistosetuptherequiredcomponents.The

ColorChooserDemoisasubclassofJFramewithmembervariablesto

holdthescreenshot(background_image),thepaneltodrawthe

image(image_panel),theJLabeltodisplaythecurrentcolorunder

thecursor(label),andafewsupportvariables.Thebeginnings

ofthisclassareshowninExample8-6.



Example8-6.SkeletonoftheColorChooserDemo

class

publicclassColorChooserDemoextendsJFrame



implementsMouseListener,MouseMotionListener{























JPanelimage_panel;

Dimensionscreen_size;

JComponentcomp=null;

Imagebackground_image=null;

Robotrobot;

JLabellabel;



publicColorChooserDemo(JComponentcomp){



//getthescreendimensions



screen_size=Toolkit.getDefaultToolkit().getSc















































































































}



//setuptheframe(this)

this.addMouseListener(this);

this.addMouseMotionListener(this);

this.comp=comp;

this.setUndecorated(true);

this.setSize(screen_size.width,screen_size.hei



//setupthepanelthatholdsthescreenshot

image_panel=newJPanel(){



publicvoidpaintComponent(Graphicsg)





super.paintComponent(g);





g.drawImage(background_image,0,



}

};

image_panel.setPreferredSize(screen_size);

this.getContentPane().add(image_panel);



//setupthedisplaylabel

label=newJLabel("SelectedColor");

label.setOpaque(true);

label.setSize(100,100);

image_panel.setLayout(null);

image_panel.add(label);

label.setLocation((int)screen_size.getWidth()/2

(int)screen_size.getHeight()/2-50);



Initsconstructor,theColorChooserDemoacceptsaJComponentto

storetheselectedcolorin.Next,thecodegetsthecurrent

screensizefromtheAWTToolkit,andthenfollowstheusual

litanyoflistenersandsetters.Notethecallto

setUndecorated(true),whichturnsoffthewindowcontrols.This

addstotheillusionthattheuserisclickingontherealsystem

desktopandnotascreenshot.



Theimage_panelisastandardJPanelwiththepaintComponent()

methodoverriddentodrawthescreenshotimageoverits

background.Itisalsosettofillthescreenwith

setPreferredSize(screen_size),andthenisaddedtotheframe.

Beforereturning,theColorChooserDemoconstructorcreatesa100x

100pixelJLabeltodisplaythecurrentselectedcolor.Bydefault,

thelabelwouldletitsparentcomponent(thescreenshot)show

throughinsteadoffillingitsbackgroundwiththeselectedcolor,

sothecodecallssetOpaque(true)tomakesurethebackgroundis

visible.Finally,thelabelismovedtothemiddleofthescreen,

calculatedbydividingthescreendimensionsinhalfand

subtractinghalfofthelabelsize.OfcourseaLayoutManagerwould

messwiththeexplicitcoordinatessethere,soimage_panel's

layoutissettonull.Thisgetsridofthedefaultlayoutmanager,

BorderLayout,andallowstheabsolutepositioningtowork.

Nowthatthechooserframeanditscomponentsaresetup,the

frameneedstomaketheactualscreenshot.ColorChooserDemo

overridestheshow()methodtomakethescreenshotbeforethe

framepopsuponscreen.Theshow()methodusesthe

robot.createScreenCapture()tocaptureandsavethescreentothe

background_imagevariablebeforepassingcontroltothesuperclass,

asshowninthefollowingcode:



publicvoidshow(){



try{





//makethescreenshotbeforeshowingtheframe





Rectanglerect=newRectangle(0,0,







(int)screen_size.getWidth(),







(int)screen_size.getHeight());





this.robot=newRobot();





background_image=robot.createScreenCapture(re





super.show();



}catch(AWTExceptionex){





System.out.println("exceptioncreatingscreensh





ex.printStackTrace();



}



}



OncetheColorChooserDemoframeisvisible,theusercanbegin

selectingcolorsbyclickinganddragginganywhereonthe(now

fake)screen.ThemousePressed(),mouseDragged(),andmouseReleased()

methodsofthemouse/mouse-motionlistenerimplementation

updatetheselectedcoloroneachmouseevent.setSelectColor()

doestheactualupdatebysettingthebackgroundcoloronboth

thelabel(whichtheusercansee)andthecomponentthatwas

passedintotheconstructor(currentlyhiddenbehindthe

frame):



//updatetheselectedcoloronmousepress,dragged,andrelea

publicvoidmousePressed(MouseEventevt){



setSelectedColor(robot.getPixelColor(evt.getX(),evt.ge

}

publicvoidmouseDragged(MouseEventevt){



setSelectedColor(robot.getPixelColor(evt.getX(),evt.ge

}

//forreleasedwewanttohidetheframeaswell

publicvoidmouseReleased(MouseEventevt){



setSelectedColor(robot.getPixelColor(evt.getX(),evt.get



this.setVisible(false);

}

//updateboththedisplaylabelandthecomponentthatwaspas

publicvoidsetSelectedColor(Colorcolor){



comp.setBackground(color);



label.setBackground(color);

}

//no-opsfortherestofthemouse-eventlistener

publicvoidmouseClicked(MouseEventevt){}

publicvoidmouseEntered(MouseEventevt){}

publicvoidmouseExited(MouseEventevt){}

publicvoidmouseMoved(MouseEventevt){}



Whentheuserreleasesthemouse,themouseReleased()method

willdoonelastcolorupdateandthenhidetheframe.Thisway,

whentheuserisdoneselectingacolor,thefinalcolorwillbe

visibleasthebackgroundofthelaunchingcomponent,asseen

inFigure8-4.



Figure8-4.Afteracolorischosen



Launchingthedemojustrequiresacomponenttocallshow()on

theColorChooserDemo:



publicstaticvoidmain(String[]args){



JFrameframe=newJFrame("ColorChooserHack");



finalJButtonbutton=newJButton("Clicktochooseac



button.addActionListener(newActionListener(){





publicvoidactionPerformed(ActionEventevt){







JFrameframe=newColorChooserDemo(but







frame.show();



}





});

















}



frame.getContentPane().add(button);

frame.pack();

frame.setVisible(true);



Andthat'sit!Nowyoucanaddfull-screencolorchoosingtoany



componentwithoutrequiringnativeaccessatall.Asan

improvement,youcouldmakethepreviewactuallyshowa

magnifiedviewofwherethecursorisinsteadofjustthe

selectedcolor.



Hack60.ChangingFontsThroughoutYour

Application



Getaquickfontface-lift,withouthavingtowriteawhole

LookandFeel.

Withnostandardsdocumentstoobeyandmoreflexibleuser

expectations,webdesignersgetmuchmorefreedomwiththeir

fontsthanSwingdevelopersexpect.Theygettosetfontstyles

withCSS,whilewe'reexpectedtojustleavewellenoughalone.

Sure,youcanchangefontsonacomponent-by-component

basiswithsetFont(),butit'snotlikeyoucanjustsay"fromnow

on,IwantallJLabelstousetheCheeseDeluxeDemi-Boldfont."

Well,OK,youcouldcreateasubclassofJLabeltosetthatfontin

itsconstructor,butyourchangewouldn'tbepickedupbyanyof

JLabel'ssubclasses,likethedefaultrenderersforlist,table,and

treecells.Fortunately,thereisamucheasierwaythanfighting

withsingleinheritance.

Swingcomponentsgetmanyoftheirdefaults(e.g.,fonts,icons,

borders),fromaHashtableownedbytheUIManagerclass.Actually,

itisasubclassofHashtable,calledUIDefaults,whichoffers

stronglytypedmethodslikegetFont(),getBorder(),getColor(),etc.,

eachofwhichtakesakeyobject.

Now,sincethisisjustaHashtable,youcanputstuffinjustas

easilyasyoucangetitout.Allyouhavetodoisknowwhatthe

keyis.Asitturnsout,forfonts,thekeysareStringsthatend

witha.fontsuffix.So,fordemonstrationpurposes,youcan

iteratethroughthekeysoftheUIDefaults,andeverytimeyou

findonethatendsin.font,puttheFontofyourchoicebackinto

theUIDefaults.



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)



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

Hack 59. Create a Color Eyedropper

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

×