Tải bản đầy đủ - 0 (trang)
Hack 91. Check Your Mail with Swing

Hack 91. Check Your Mail with Swing

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

TheEmailCheckerclass,showninExample12-5,isasimple

RunnableimplementationthatreceivesaJLabeltoitsconstructor.

Therunloopwillsleepforacertainamountoftime(oneminute

inthiscase)thencallcheckEmail().Everytimethereisnewmail,

itwillsetthetextofthelabeltosomethinglike"YouhaveNnew

messages."



Example12-5.Checkingfornewmessages











importjava.util.Properties;

importjavax.swing.JLabel;

importjavax.swing.SwingUtilities;

importjavax.mail.*;















publicclassEmailCheckerimplementsRunnable{



privateJLabellabel;



publicEmailChecker(JLabellabel){





this.label=label;



}











































publicvoidrun(){



while(true){







try{





checkEmail();





Thread.currentThread().sleep(10





}catch(Exceptionex){





System.out.println("exception:





ex.printStackTrace();





























}





}



}



NextcomesthecheckEmail()implementation:













publicsynchronizedvoidcheckEmail()throwsException



Stringusername="joshy@code.joshy.org";



Stringpassword="satans";



Stringhostname="code.joshy.org";



intport=143;



















Propertiesprops=System.getProperties();

Sessionsess=Session.getDefaultInstance(props

sess.setDebug(true);



Toactuallychecktheemail,youneedtofirstcollectthe

relevantparameters:theusername,password,hostnameofthe

emailserver,andtheport(usually143forIMAPservers).In

additiontothisinformation,youalsoneedacopyofthesystem

propertiestoallocateanemailSession.



Inamoreadvancedversionofthishack,youcouldoverridesomeof

thesystempropertiestochangetheinstalledemailproviderormodify

othersettings.



Onceyouhavethesession,youcanopenanIMAPemailstore

andconnecttoit:







Storestore=sess.getStore("imap");

store.connect(hostname,port,username,password);









Folderinbox=store.getFolder("INBOX");

finalintnew_count=inbox.getUnreadMessageCount();







SwingUtilities.invokeLater(newRunnable(){







publicvoidrun(){







label.setText("Youhave"+new_count+







System.out.println("unreadmessages="





}



});

}//endcheckEmail()



Thiscodeconnectstotheemailstoreandthenopensthe

INBOXfolder.Someemailserversmayuseadifferentnamefor

theinboxfolder,butINBOXshouldsufficeformostIMAP

servers.Finally,youcangettheunreadmessagecount.Once

youhaveobtainedthenewmessagecount,youcansetthetext

ofthelabel.It'simportanttodothisontheSwingthread,

however,whichiswhythecodeusesSwingUtilities.invokeLater()

toperformtheoperation.

Thesecondtaskforthishackistoactuallylaunchtheuser's

emailprogram.Detectingthedefaultemailprogramisdifficult

anderrorprone.Ifyoudon'twanttouseanativelibrarylike

JDIC,thenyouronlyoptionistoasktheuserwherehis

programisandlaunchitwithRuntime.exec().Example12-6takes

careofthis,whichturnsouttobemercifullysimple.



Example12-6.Askingtheuserforanemail

program



















importjava.awt.event.MouseAdapter;

importjava.awt.event.MouseEvent;

publicclassEmailLauncherextendsMouseAdapter{



publicvoidmousePressed(MouseEventevt){





if(evt.getClickCount()>=2){







launchEmailReader();







evt.consume();





}











}



















publicvoidlaunchEmailReader(){





try{







Runtimert=Runt1ime.getRuntim







rt.exec("C:\\ProgramFiles\\Moz





}catch(Exceptionex){







System.out.println(ex.getMessag







ex.printStackTrace();















}





}



}



IimplementedEmailLauncherasamouselistenerthatlooksfora

double-click,whichmakesitveryeasytoaddtoanycomponent

withasimpleaddMouseListener()call.Ihavehardcodedthepath

tomyemailprogram,butamoreadvancedversionofthishack

woulduseapreferencesscreentoasktheuser.

Example12-7isasimpleprogramthatcreatesaframewith

oneJLabeltoshowthemailstatus.ItattachesanEmailLauncherto

thestatuslabelasamouselistenerandthenlaunchesthe

EmailCheckerinitsownthreadjustbeforemakingtheframe

visible.



Example12-7.Testingouttheemailutilities















publicclassEmailTest{



publicstaticvoidmain(String[]args){





JFrameframe=newJFrame("Hack#91





JLabelstatus=newJLabel("YouhaveXX





frame.getContentPane().add(status);





frame.pack();



























status.addMouseListener(newEmailLaunch

EmailCheckeremail=newEmailChecker(s

newThread(email).start();















}





}



frame.setVisible(true);



Onceyoucompiletheprogramandrunit,youshouldsee

somethinglikeFigure12-4.

Thisisaprettysimplehack,butitshouldgiveyouinspirationto

tryotherembeddedfeatures,suchascheckingRSSfeedsor

playingMP3s.



Figure12-4.Emailcheckerrunning



Foramoregraphicaleffect,youcouldusetheemailiconsfrom

thewindowssystemfonts.WebDingsandWingDingscontain

theemailiconsshowninFigures12-5and12-6.



Figure12-5."HaveMail"icon



Figure12-6."NoMail"icon



However,Windowsdoesstrangecodepagemapping,sothese

fontsaren'tsimpletranslationsofletterstosymbols.Instead,

youwillhavetousethetrueUnicodevaluesfortheglyphsyou

want:





























});



SwingUtilities.invokeLater(newRunnable(){



publicvoidrun(){





//label.setText("Youhave"+new_count





if(new_count>0){







label.setFont(newFont("WebDing







Font.PLAIN,40));//label.getFont





label.setText(""+(char)0xf099);



}else{





label.setFont(newFont("WingDings",







Font.PLAIN,40));//label.getFont





label.setText(""+(char)0x2709);



}



System.out.println("unreadmessages="+new_c

}



Thiscodewillsetthelabeltocharacter0xf099intheWebDings

font(theenvelopewithalightningbolt)ifthereisatleastone

unreademail.Iftherearenounreademails,itwilluse

character0x2709intheWingDingsfont(aplainenvelope).



Javadoesn'tsupportalloftheglyphsincertaincustomfonts,sobe

suretotestyourapplicationsbeforegoingintoproductionwhenever

youusenon-ASCIIfonts.



Hack92.Don'tBlocktheGUI



Threadyourheavyliftingsotheevent-dispatchthread

staysresponsive.

PracticallyeveryAWTandSwingbookyou'lleverseekeeps

thingssimplebyrespondingtobuttonclicks,menuselections,

andotheractionsbydoingsomethingintheeventlistener.

That'sprobablygoodforhelpingyoulearnthevariousGUI

widgets,butitsetsyouupforareallybadhabit:putting

increasinglylong-lastingcallsinyoureventcallbacks.

ThisisbadbecausethethreadthatcallsactionPerformed(),

valueChanged(),andotherevent-basedmethodsisthesame

threadthatservicesGUIeventsthroughoutAWTandSwing.

TheAWTEventDispatchThreadisresponsibleforpollingfor

events,dispatchingthemtolisteners,andforrepainting

everything.Ifyoublockitonsomelong-lastingcallsuchas

databaseornetworkaccess,intensecalculation,etc.then

mouseclicksandkey-presseswon'tbeprocessed,menuswon't

beavailable,portionsofyourGUImaynotgetrepaintedifthey

becomeobscuredbyotherwindows,etc.Oh,andtheuserwill

hateyou.Justsoyouknow.

Thetrick,then,istokeepheavyliftingoutoftheeventdispatchthread.There'saverystraightforwardwaytodothisin

Java:movecomplicatedprocessingtoitsownthread,andlet

eventdispatchingcontinueimmediatelyafterstartingthisnew

thread.Thenyoujusthavetodealwithcleanupwhenthe

launchedthreadfinishesup.

AWTBlockDemo,showninExample12-8,offersatestbedfor



exhibitingandfixingtheproblem.ItoffersaJTextFieldalong



withtwoJButtons:Load(blocking)andLoad(non-blocking).A

menualsoofferstheblockingandnon-blockingloadas

JMenuItems,alongwithaQuitmenuitem.

ThetextfieldtakesaURL.Whenyouclickoneoftheload

buttonsormenuitems,itloadsthefileatthataddressintothe

textarea.Thetextareaispre-populatedwiththeaddressfor

java.awt.ComponentinSun'sJavaDoc,anice300KBfilethatwill

takealittlewhiletoload,evenwithafastnetworkconnection.



Ifyournetworkisreallyfast,youcanputsomeTHRead.sleep()callsin

thecodetosimulateaslowernetwork.



ThecodeforthedemoisshowninExample12-8.



Example12-8.Demonstrationofbothblocking

andnotblockingtheAWTevent-dispatchthread

duringlengthyactions













importjava.awt.*;

importjava.awt.event.*;

importjavax.swing.*;

importjava.io.*;

importjava.net.*;

















publicclassAWTBlockDemoextendsJFrame{



JButtonblockButton,dontBlockButton;



JMenuItemblockMenuItem,dontBlockMenuItem,qui



JTextFieldurlField;



JTextAreacontentArea;



finalstaticStringDEFAULT_URL=



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

Hack 91. Check Your Mail with Swing

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

×