Tải bản đầy đủ - 0 (trang)
Hack 58. Block a Window Without a Modal Dialog

Hack 58. Block a Window Without a Modal Dialog

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

Sinceyouwantyourglasspanetobetransparent,it'sbestto

startwithaplainJComponentthatdoesn'tdrawanything.Example

8-3definesaWindowBlockerclassthatextendsJComponentand

implementstheMouseInputListener(acompoundinterfacethat

combinestheMouseListenerandMouseMotionListener).



Example8-3.Listeningformouseevents

publicclassWindowBlockerextendsJComponent



implementsMouseInputListener{





publicWindowBlocker(){





addMouseListener(this);





addMouseMotionListener(this);



}





publicvoidmouseMoved(MouseEvente){



}



publicvoidmouseDragged(MouseEvente){



}



publicvoidmouseClicked(MouseEvente){



}



publicvoidmouseEntered(MouseEvente){



}



publicvoidmouseExited(MouseEvente){



}



publicvoidmousePressed(MouseEvente){







Toolkit.getDefaultToolkit().beep();



}



publicvoidmouseReleased(MouseEvente){



}



Sofar,thecodeisprettysimple.TheWindowBlockercatchesall



mouseeventsanddoesnothing,sendingtheeventstothat

greatbitbucketinthesky.Whentheuserpressesthemouse,

thecomputerwillbeep,indicatingthatthewindowisbusy.The

componentstillwon'tactuallyreceiveeventsbecauseitis

invisiblebydefault.Whenyouarereadytostartblocking

events,youshouldmakethecomponentvisible.That'swhere

theblock()methodcomesin:



privateCursorold_cursor;

publicvoidblock(){



old_cursor=getCursor();



setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR



setVisible(true);

}





publicvoidunBlock(){



setCursor(old_cursor);



setVisible(false);

}



Beforesettingthecomponenttovisible,youshouldsavethe

currentmouseimageandthenchangeittoabusycursor.The

cursorwillonlybeineffectoverthecomponentyoucall

setCursor()on,soonlytheblockedwindowwillgetthebusy

signal.Allotherwindowswillstillusetheirnormalcursors.

Whenunblock()iscalled,youcanrestorethecursorandhidethe

WindowBlockercomponentagain.



8.4.2.BuildaTestProcess

Totestthewindowblocker,youwillneedsomesortoflongrunningprocess.TheclassinExample8-4,LongProcess,willstart

a10-secondcountdownwhenitsactionPerformed()methodis

called.Itwillalsoprintthecurrenttimeleftinastatuslabel.



NotethatthecalltosetText()onthestatuslabelisinsideofa

SwingUtilities.invokeLater()method.ThismakessurethatsetText()

iscalledfromtheSwingeventthread,avoidinganythreading

issuesordeadlock.



Example8-4.Fillingupclockcycles



classLongProcessimplementsActionListener,Runnable{



JLabelstatus;



WindowBlockerblocker;



publicLongProcess(JLabelstatus,WindowBlockerblocker





this.blocker=blocker;





this.status=status;



}

publicvoidactionPerformed(ActionEventevt){





blocker.block();





new

Thread(this).start();



}

publicvoidsetText(finalStringtext){



SwingUtilities.invokeLater(newRunnable(){





publicvoidrun(){







status.setText(text);





}



});

}

publicvoidrun(){



for(inti=10;i>0;i--){





//setthelabel





finalStringtext="("+i+")secondsleft";





setText(text);













//sleepfor1second

try{



















}

















}





Thread.currentThread().sleep(1000);



}catch(Exceptionex){



}

}

//setthefinalstatusstring

setText("ProcessComplete");

blocker.unBlock();



8.4.3.PuttingItAllTogether

Withyourwindowblockingandlong-processclassesready,you

canputthemtogetherinasimpleprogram.Themain()method

inExample8-5createsatextarea,abutton,andastatuslabel.

ThenitmakesaWindowBlockerandinstallsitwith

frame.setGlassPane().TheLongProcessisaddedasanactionlistener

totheStartbutton,sowhentheuserpressesStartProcessing,

theprocesswilllaunchandcallWindowBlocker.block().Oncethe

processends,itwillcallWindowBlocker.unBlock(),releasingthe

window.



Example8-5.Testingtheblockingwindow

publicstaticvoidmain(String[]args){



JFrameframe=newJFrame("BlockingWindow");



JTextAreajta=newJTextArea(10,40);



JScrollPanescroll=newJScrollPane(jta);



JButtonstart=newJButton("StartProcessing");



JLabelstatus=newJLabel("status");





WindowBlockerblocker=newWindowBlocker();









frame.setGlassPane(blocker);

start.addActionListener(newLongProcess(status,blocker)













Containercomp=frame.getContentPane();

comp.add("North",start);

comp.add("Center",scroll);

comp.add("South",status);







}



frame.pack();

frame.show();



Hack59.CreateaColorEyedropper



Enhanceyourcolorpickerswithaneyedroppertoolthat

grabsacolorfromanywhereonthescreen.

Mostpainttoolsgiveyouaneyedropper,butI'veneverseena

Javaprogramdoit.Gettingascreenpixelrequiresnative

access,whichisusuallyblockedofffromJavaprograms.Java

1.3introducedanewmethodtotheRobotclass,getPixelColor(),

whichcanretrievethecoloranywhereonthescreen.The

problemisthatyoudon'tgetmouseeventsoncethecursor

leavesyourJFrame.Thisisfineifyouonlywanttoselectcolors

fromyourownapplication,butacolorchooserneedstoselect

fromanywhereonthescreen.Java5.0introducesnewAPIsfor

gettingcompletemouseevents,butthatdoesn'thelpustoday.

Theanswertothistrickyproblem,ofcourse,istocheat!This

hackmakesascreenshotandthenpaintsitintoaJFramecalled

ColorChooserDemo,whichfillstheentirescreen.Thescreenshotis

indistinguishablefromtherealdesktopexceptthatnothingin

thebackgroundupdates.However,sincethescreenshotisonly

neededwhiletheuserselectsacolor,thisshouldbeOK.

ColorChooserDemoalsohasaJLabelinthecenterofthescreen,

whichdisplaysthecurrentlyselectedcolor.Oncetheuserhas

finishedselectingacolorbyreleasingthemouse,theentire

framewilldisappearandthecomponentthatlaunchedthe

chooserusuallyaJButtonwillgetthecolorthroughsetBackground().

Whileit'srunning,ColorChooserDemolookslikeFigure8-3.



Figure8-3.RunningtheColorChooserDemo



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



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

Hack 58. Block a Window Without a Modal Dialog

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

×