Java Thread Programming 1.9.2-Threads and Swing

Source: Internet
Author: User
Using a Worker Thread to Relieve the Event ThreadUse a working Thread for transaction operations/** Created on 2005-7-17 ** Java Thread Programming-Paul Hyde * Copyright? 1999 Sams Publishing * Jonathan Q. bo Study Notes **/package org. tju. msnrl. jonathan. thread. chapter9; import java. awt. *; import java. awt. event. *; import javax. swing. *;/*** @ author Jonathan Q. bo from tju msnrl ** E-mail: jonathan.q.bo@gmail.com * Blog: blog.csdn.net/jonathan_q_bo * blog.yesky.net/jonathanundersun ** Enjoy Life with Sun! **/Public class BalanceLookUp extends JPanel {private JTextField accTF; private JTextField pinTF; private JButton searchB; private JButton cancelB; private JLabel balanceL; private volatile Thread lookupThread; public BalanceLookUp () {buildGUI (); // control display hookupEvent (); // Add event processing}/** add control */public void buildGUI () {JLabel accountL = new JLabel ("Account Label"); JLabel pinL = new JLabel ("Pin"); accT F = new JTextField (12); pinTF = new JTextField (4); JPanel dataP = new JPanel (); dataP. setLayout (new FlowLayout (FlowLayout. CENTER); dataP. add (accountL); dataP. add (accTF); dataP. add (pinL); dataP. add (pinTF); searchB = new JButton ("search"); cancelB = new JButton ("cancel"); cancelB. setEnabled (false); JPanel buttonP = new JPanel (); buttonP. setLayout (new GridLayout (1,-1, 5, 5); buttonP. add (searchB); TonP. add (cancelB); JPanel outButtonP = new JPanel (); outButtonP. setLayout (new FlowLayout (FlowLayout. CENTER); outButtonP. add (buttonP); JLabel balancePrifLb = new JLabel ("account balance"); this. balanceL = new JLabel ("unknown balance"); JPanel balanceP = new JPanel (); balanceP. setLayout (new FlowLayout (FlowLayout. CENTER); balanceP. add (balancePrifLb); balanceP. add (balanceL); JPanel northP = new JPan El (); northP. setLayout (new GridLayout (-1, 1, 5); northP. add (dataP); northP. add (outButtonP); northP. add (balanceP); setLayout (new BorderLayout (); add (northP);}/** add Event Response Function */public void hookupEvent () {searchB. addActionListener (new ActionListener () {public void actionreceivmed (ActionEvent e) {search () ;}}); cancelB. addActionListener (new ActionListener () {public void actionreceivmed (ActionEve Nt e) {cancelSearch () ;}}) ;}/ ** process search operation */private void search () {this. ensureEventThread (); searchB. setEnabled (false); cancelB. setEnabled (true); balanceL. setText ("searching... "); String account = accTF. getText (); String pin = pinTF. getText ();/* Create a New thread for processing, view the account balance based on the account and password */lookupAsyn (account, pin );} /** cancel Operation Processing */private void cancelSearch () {this. ensureEventThread (); cancelB. setEnabled (false); sear ChB. setEnabled (true); if (lookupThread! = Null) {lookupThread. interrupt () ;}}/** new thread processing view operation */private void lookupAsyn (String acc, String pin) {final String accN = acc; final String pinN = pin; runnable runA = new Runnable () {public void run () {String bal = lookupBalance (accN, pinN); setBalanceSaftly (bal) ;}; lookupThread = new Thread (runA ); lookupThread. start ();}/** secure display balance */private void setBalanceSaftly (String bal) {final String balN = bal; Runnable runA = new Runnable () {public void run () {try {setBalance (balN);} catch (Exception e) {e. printStackTrace () ;}};/* put in the message queue and wait for processing. */SwingUtilities is returned. invokeLater (runA);}/** show balance */private void setBalance (String bal) {this. ensureEventThread (); balanceL. setText (bal); cancelB. setEnabled (false); searchB. setEnabled (true);}/** actually these two parameters are useless */private String lookupBalance (String acc, String pin) {try {Thread. sleep (5000); return "1,234.5";} catch (InterruptedException e) {return "search canceled ";}} /** ensure that the message thread executes */private void ensureEventThread () {if (SwingUtilities. isEventDispatchThread () = false) throw new RuntimeException ("only event thread can do this"); return;} public static void main (String [] args) {BalanceLookUp blp = new BalanceLookUp (); JFrame f = new JFrame ("Balance Lookup"); f. addWindowListener (new WindowAdapter () {public void windowClosing (invalid wevent e) {System. exit (0) ;}}); f. setContentPane (blp); f. setSize (400,150); f. setVisible (true );}} Scrolling Text in a Custom ComponentAnimation effect: Scroll subtitle/** created on 2005-7-18 ** Java Thread Programming-Paul Hyde * copyright? 1999 SAMs publishing * Jonathan Q. bo Study Notes **/package Org. tju. msnrl. jonathan. thread. chapter9; import javax. swing. *; import Java. AWT. *; import Java. AWT. event. *; import Java. AWT. font. *; import Java. AWT. image. *;/** provides the Java 2D Classes * for defining and naming operations * on objects * related to two-dimen1_geometry. * // * provides two-dimensional geometric operations */import Java. AWT. geom. *;/*** @ author Jonathan Q. bo F Rom tju msnrl ** E-mail: jonathan.q.bo@gmail.com * blog: blog.csdn.net/jonathan_q_bo * blog.yesky.net/jonathanundersun ** enjoy life with sun! **/Public class scrolltext extends jcomponent {private bufferedimage image; private dimension imagesize; Public volatile int curroffset; private thread localthread; private volatile Boolean nostoprequest; Public scrolltext (string text) {curroffset = 0; buildimage (text); this. setmaximumsize (this. imagesize); this. setminimumsize (this. imagesize); this. setpreferredsize (this. imagesize); this. setsize (this. imagesize); this. nostoprequest = true; runnable Runa = new runnable () {public void run () {try {runwork ();} catch (exception e) {e. printstacktrace () ;}}; localthread = new thread (Runa, "scrolltext"); localthread. start ();} public void paint (Graphics g) {G. setclip (0, 0, this. imagesize. width, imagesize. height); int localoffset = curroffset; G. drawimage (this. image,-localoffset, 0, this); G. drawimage (this. image, imagesize. width-localoffset, 0, this); G. setcolor (color. black); G. drawrect (0, 0, imagesize. width-1, imagesize. height-1);} public void stopthread () {This. nostoprequest = false; localthread. interrupt ();} public Boolean isalive () {return localthread. isalive ();} private void buildimage (string text) {renderinghints renderhints = new renderinghints (renderinghints. key_antialiasing, renderinghints. value_antialias_on); renderhints. put (renderinghints. key_rendering, renderinghints. value_render_quality); bufferedimage scratchimage = new bufferedimage (1, 1, bufferedimage. type_int_rgb); graphics2d scratchg2 = scratchimage. creategraphics (); scratchg2.setrenderinghints (renderhints); font = new font ("serif", Font. bold | font. italic, 24); fontrendercontext FRC = scratchg2.getfontrendercontext (); textlayout TL = new textlayout (text, Font, FRC); rectangle2d textbounds = TL. getbounds (); int textwidth = (INT) math. ceil (textbounds. getwidth (); int textheight = (INT) math. ceil (textbounds. getheight (); int horizpad = 10; int verticpad = 6; this. imagesize = new dimension (textwidth + horizpad, textheight + verticpad); this. image = new bufferedimage (imagesize. width, imagesize. height, bufferedimage. type_int_rgb); graphics2d g2 = image. creategraphics (); g2.setrenderinghints (renderhints); int baselineoffset = (verticpad/2)-(INT) (textbounds. gety (); g2.setcolor (color. white); g2.fillrect (0, 0, imagesize. width, imagesize. height); g2.setcolor (color. blue); TL. draw (G2, 0, baselineoffset); scratchg2.dispose (); scratchimage. flush (); g2.dispose ();} private void runwork () {While (nostoprequest) {try {thread. sleep (100); curroffset = (curroffset + 1) % This. imagesize. width; repaint ();} catch (interruptedexception e) {thread. currentthread (). interrupt (); system. out. println ("interruptedexception" + E. getmessage () ;}} public static void main (string [] ARGs) {scrolltext ST = new scrolltext ("Java can do Animation "); jpanel P = new jpanel (New flowlayout (); p. add (ST); jframe F = new jframe ("scroll text Demo"); F. setcontentpane (p); F. setsize (400,200); F. setvisible (true );}} Animating a Set of ImagesAnimation effect: Dynamic Scaling of an elliptic/** Created on 2005-7-19 ** Java Thread Programming-Paul Hyde * Copyright? 1999 Sams Publishing * Jonathan Q. bo Study Notes **/package org. tju. msnrl. jonathan. thread. chapter9; import java. awt. *; import java. awt. image. *; import javax. swing. *;/*** @ author Jonathan Q. bo from tju msnrl ** E-mail: jonathan.q.bo@gmail.com * Blog: blog.csdn.net/jonathan_q_bo * blog.yesky.net/jonathanundersun ** Enjoy Life with Sun! **/Public class SlideShow extends JComponent {private BufferedImage [] slide; // The displayed image private Dimension slideSize; // The slice size private volatile int currSlide; // The Slice private Thread internalThread to be displayed; // The New Thread executes the update private volatile boolean noStopRequested; // identifies the Thread to stop public SlideShow () {currSlide = 0; /* set the control size */slideSize = new Dimension (50, 50);/* plot in cache */buildSlides ();/* set it to a fixed size */setMinimumSize (slideSize ); setPreferredSize (slideSize); setMaximumSize (slideSize); setSize (slideSize); noStopRequested = true; Runnable r = new Runnable () {public void run () {try {runWork ();} catch (Exception e) {e. printStackTrace () ;}};/* Self-running object */internalThread = new Thread (r, "SlidwShow"); internalThread. start ();} public void paint (Graphics g) {/* draw the current slide */g. drawImage (slide [currSlide], 0, 0, this);} private void buildSlides () {RenderingHints renderHints = new RenderingHints (RenderingHints. KEY_ANTIALIASING, RenderingHints. VALUE_ANTIALIAS_ON); renderHints. put (RenderingHints. KEY_RENDERING, RenderingHints. VALUE_RENDER_QUALITY); slide = new BufferedImage [20]; Color rectColor = new Color (100,160,250); Color circleColor = new Color (250,250,150 ); /* draw each slide */for (int I = 0; I <slide. length; I ++) {slide [I] = new BufferedImage (slideSize. width, slideSize. height, BufferedImage. TYPE_INT_RGB);/* obtain Graphics control */Graphics2D g2 = slide [I]. createGraphics ();/* Set renderhint */g2.setRenderingHints (renderHints);/* fill the rectangle */g2.setColor (rectColor); g2.fillRect (0, 0, slideSize. width, slideSize. height);/* draw an ellipse between 5 and 45 */g2.setColor (circleColor); int diameter = 0; if (I <(slide. length/2) {diameter = 5 + (8 * I);} else {diameter = 5 + (8 * (slide. length-I);} int inset = (slideSize. width-diameter)/2; g2.fillOval (inset, inset, diameter, diameter);/* draw a Rectangular Box */g2.setColor (Color. BLACK); g2.drawRect (0, 0, slideSize. width-1, slideSize. height-1);/* release resources */g2.dispose () ;}} private void runWork () {while (noStopRequested) {try {Thread. sleep (100);/* rotate images */currSlide = (currSlide + 1) % slide. length;/* update display */repaint ();} catch (InterruptedException e) {Thread. currentThread (). interrupt (); e. printStackTrace () ;}} public void stopRequest () {noStopRequested = false; internalThread. interrupt ();} public static void main (String [] args) {SlideShow ss = new SlideShow (); JPanel p = new JPanel (new FlowLayout (); p. add (ss); JFrame f = new JFrame ("SlideShow Demo"); f. setContentPane (p); f. setSize (250,150); f. setVisible (true );}} Displaying Elapsed Time on a JLabel  Animation effect: display the elapsed time in a jlabel/** created on 2005-7-19 ** Java Thread Programming-Paul Hyde * copyright? 1999 SAMs publishing * Jonathan Q. bo Study Notes **/package Org. tju. msnrl. jonathan. thread. chapter9; import javax. swing. *; import Java. AWT. *; import Java. text. *; import Java. lang. reflect. *;/*** @ author Jonathan Q. bo from tju msnrl ** E-mail: jonathan.q.bo@gmail.com * blog: blog.csdn.net/jonathan_q_bo * blog.yesky.net/jonathanundersun ** enjoy life with sun! **/Public class digitaltimer extends jlabel {private volatile string timetext; private thread internalthread; private volatile Boolean nostoprequested; Public digitaltimer () {This. setborder (borderfactory. createlineborder (color. black); this. sethorizontalalignment (swingconstants. right); this. setfont (new font ("sansserif", Font. bold, 16);/* used to determine the control size */This. settext ("00000.0"); this. setminimumsize (getpreferredsize (); this. setpreferredsize (this. getpreferredsize (); this. setsize (this. getpreferredsize (); timetext = "0.0"; this. settext (timetext); nostoprequested = true; runnable r = new runnable () {public void run () {try {runwork ();} catch (exception e) {e. printstacktrace () ;}};/* Self-running object */internalthread = new thread (R, "digitaltimer"); internalthread. start ();} private void runwork () {long starttime = system. currenttimemillis (); // start time int tenths = 0; // The number of thread executions long normalsleeptime = 100; // The normal interval long nextsleeptime = 100; // next interval decimalformat FMt = new decimalformat ("0.0");/* update Label display */runnable updatetext = new runnable () {public void run () {settext (timetext) ;}}; while (nostoprequested) {try {/* high real-time requirements */thread. sleep (nextsleeptime);/* While execution times plus */tenths ++; long currtime = system. currenttimemillis (); // The current time long elapsedtime = currtime-starttime; // The actual past time/* The next thread rest time should be adjusted at the interval, actual elapsed time and expected elapsed time query value */nextsleeptime = normalsleeptime + (tenths * 100)-elapsedtime);/* if it is negative, set it to 0 */If (nextsleeptime <0) nextsleeptime = 0;/* notification display */timetext = FMT. format (elapsedtime/1000.0); swingutilities. invokeandwait (updatetext);} catch (interruptedexception E1) {e1.printstacktrace ();/* Stop running */return;} catch (invocationtargetexception E2) {e2.printstacktrace ();}}} public static void main (string [] ARGs) {digitaltimer dt = new digitaltimer (); jpanel P = new jpanel (New flowlayout (); p. add (DT); jframe F = new jframe ("digitaltimer Demo"); F. setcontentpane (p); F. setsize (250,100); F. setvisible (true );}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.