Results 1 to 8 of 8
  1. #1
    NotTooOld is offline Hostage
    Join Date
    Apr 2013
    Location
    China
    Posts
    128
    Rep Power
    0

    Default Muti Thread? Sleep()?? Timer?? none of these seem to work for me.

    Back again with more questions. I'm trying to do something that should be simple: Disable all buttons long enough for an animated gif to run, then Enable them all again.
    I've tried Thread.Sleep(), but no matter where I put it, it always "sleeps" the drawing of the animated gif. (though the animation keeps running, after the sleep time it jumps forward to the end) I've tried putting a Timer in most any method (including main) and get the same thing. And all my attempts to use a Thread (and sleep that Thread) to delay Enabling the buttons gives me null exceptions. My latest attempt put the "Timer" Thread in a new class... still no dice.
    I really want to get rid of the "Reset Button."
    Please look at the code and give me any suggestions you might have.

    Code: --- Sorry, most all the formatting went away when I submitted this post.
    Java Code:
    public class AlphaPlay extends JFrame implements ActionListener{
    
    		private JPanel contentPane;
    		private String imgLeft = "C:\\Eclipse\\AlphaPlay\\files\\" +
    				"ZZOpen\\LeftHand.gif";
    		private String imgTop = "C:\\Eclipse\\AlphaPlay\\files\\" +
    				"ZZOpen\\TopStart.gif";
    		private String imgRight = "C:\\Eclipse\\AlphaPlay\\files\\" +
    				"ZZOpen\\report.gif";
    		private JLabel ImageLeft = new JLabel("");
    		private JLabel ImageTop = new JLabel("");
    		private JLabel ImageRight = new JLabel("");
    		final JButton btnA, btnB, btnC, btnD, btnE, btnF, btnG, btnH, btnI, btnJ, btnK, btnL,
    				btnM, btnN, btnO, btnP, btnQ, btnR, btnS, btnT, btnU, btnV, btnW, btnX,
    				btnY, btnZ, btnReset;
    		final JButton allButtons[];
    		static Thread timer;
    		
    	public static void main(String[] args) {
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					AlphaPlay frame = new AlphaPlay();
    					frame.setVisible(true);
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		});
    	}
    	public AlphaPlay() {
    		setBackground(Color.LIGHT_GRAY);
    		setResizable(false);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setBounds(350, 220, 636, 494);
    		contentPane = new JPanel();
    		contentPane.setBackground(Color.WHITE);
    		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    		setContentPane(contentPane);
    		contentPane.setLayout(null);
    		allButtons = new JButton[27];
    						
    		ImageLeft.setIcon(new ImageIcon(imgLeft));		
    		ImageLeft.setBounds(68, 89, 200, 236);
    		contentPane.add(ImageLeft);
    		
    		
    		ImageTop.setIcon(new ImageIcon(imgTop));		
    		ImageTop.setBounds(58, 11, 510, 65);
    		contentPane.add(ImageTop);
    		
    		
    		ImageRight.setIcon(new ImageIcon(imgRight));		
    		ImageRight.setBounds(341, 87, 200, 238);
    		contentPane.add(ImageRight);
    		
    		JPanel keys = new JPanel();
    		keys.setBackground(Color.LIGHT_GRAY);
    		keys.setBounds(0, 344, 630, 107);
    		contentPane.add(keys);
    				
    		btnA = new JButton("A");
    		btnA.setAlignmentX(Component.CENTER_ALIGNMENT);
    		btnA.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				PlayAll(e.getActionCommand());
    			}
    		});
    		btnA.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
    		btnA.setBackground(Color.WHITE);
    		keys.add(btnA);
    		allButtons[1] = btnA;
    
                      //  ________  Here there are 25 more buttons, B-Z, but all are identical to A__________
    
    		btnReset = new JButton("               Choose Another Letter               ");
    		btnReset.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent arg0) {
    				EnableKeys();
    				btnReset.setEnabled(false);
    				timer.run();				
    			}
    		});
    		btnReset.setFont(new Font("Comic Sans MS", Font.BOLD, 14));
    		btnReset.setBackground(Color.WHITE);
    		btnReset.setEnabled(false);
    		keys.add(btnReset);
    		allButtons[0] = btnReset;				
    	}
    	public void DisableKeys() {
    		for(int i = 1; i <= 26; i++){
    			allButtons[i].setEnabled(false);		
    		}
    		if (!btnReset.isEnabled()){
    			btnReset.setEnabled(true);
    		}		
    	}
    	public void EnableKeys() {
    		for(int i = 1; i <= 26; i++){
    		allButtons[i].setEnabled(true);
    		}
    	}
    	public void PlayAll(String letter) {
    		String root = "C:\\Eclipse\\AlphaPlay\\files\\";
    		String folder = root + letter + "\\";
    		String left = folder + letter + "L.gif";
    		String top = folder + letter + "T.gif";
    		String right = folder + letter + "R.gif";
    		String sound = folder + letter + ".wav";
    		File file = new File(sound);
    		ImageIcon leftIcon = new ImageIcon(left);
    		ImageIcon topIcon = new ImageIcon(top);
    		ImageIcon rightIcon = new ImageIcon(right);
    		leftIcon.getImage().flush();
    		topIcon.getImage().flush();
    		rightIcon.getImage().flush();
    
    		try {
    			ImageLeft.setIcon(leftIcon);
    			ImageTop.setIcon(topIcon);
    			ImageRight.setIcon(rightIcon);
    		}
    		catch (Exception e){
    			e.printStackTrace();
    		}
    		try {
                AudioInputStream audio = AudioSystem.getAudioInputStream(file);
                Clip clip = AudioSystem.getClip();
                clip.open(audio);
                clip.start();
            }
            
            catch(UnsupportedAudioFileException uae) {
                System.out.println(uae);
            }
            catch(IOException ioe) {
                System.out.println(ioe);
            }
            catch(LineUnavailableException lua) {
                System.out.println(lua);
            }
    		Timer timer = new Timer();
    		timer.run();
    	}	
    	public class Timer implements Runnable {
    
    		@Override
    		public void run() {	
    			Thread timer = new Thread();
    			timer.start();
    			try {
    				timer.sleep(6000);
    				if (!btnA.isEnabled()){
    				EnableKeys();
    				}
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}			
    		}				
    	}	
    	@Override
    	public void actionPerformed(ActionEvent arg0) {
    	}
    }
    The code above only delays the start of the animation.

    Recent Stack Trace: -the line numbers are not reflective of the code above since I snipped out quite a bit.
    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at biz.mybiz.alpha.AlphaPlay.PlayAll(AlphaPlay.java:479)
    	at biz.mybiz.alpha.AlphaPlay$2.actionPerformed(AlphaPlay.java:91)
    	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    	at java.awt.Component.processMouseEvent(Unknown Source)
    	at javax.swing.JComponent.processMouseEvent(Unknown Source)
    	at java.awt.Component.processEvent(Unknown Source)
    	at java.awt.Container.processEvent(Unknown Source)
    	at java.awt.Component.dispatchEventImpl(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Window.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$200(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue$4.run(Unknown Source)
    	at java.awt.EventQueue$4.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    Last edited by JosAH; 04-07-2013 at 04:40 PM. Reason: added [code] ... [/code] tags

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,661
    Blog Entries
    7
    Rep Power
    21

    Default Re: Muti Thread? Sleep()?? Timer?? none of these seem to work for me.

    Quote Originally Posted by NotTooOld View Post
    Code: --- Sorry, most all the formatting went away when I submitted this post.
    I fixed the [code] ... [/code] tags for you; next time you can do it yourself.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    NotTooOld is offline Hostage
    Join Date
    Apr 2013
    Location
    China
    Posts
    128
    Rep Power
    0

    Default Re: Muti Thread? Sleep()?? Timer?? none of these seem to work for me.

    Quote Originally Posted by JosAH View Post
    I fixed the [code] ... [/code] tags for you; next time you can do it yourself.

    kind regards,

    Jos
    Thanks much! I try to keep my lines pretty short, but I see that one line got cut off because it was too long. No biggie! It was only a comment.
    Last edited by NotTooOld; 04-07-2013 at 05:32 PM.

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,661
    Blog Entries
    7
    Rep Power
    21

    Default Re: Muti Thread? Sleep()?? Timer?? none of these seem to work for me.

    Quote Originally Posted by NotTooOld View Post
    Thanks much! I try to keep my lines pretty short, but I see that one line got cut off because it was too long. No biggie! It was only a comment.
    You're welcome; about that cutting off: blame the silly forum software for that; it uses a very limited line size maximum ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    NotTooOld is offline Hostage
    Join Date
    Apr 2013
    Location
    China
    Posts
    128
    Rep Power
    0

    Default Re: Muti Thread? Sleep()?? Timer?? none of these seem to work for me.

    I may just set a variable to hold the last action event, and use it to disable a single button. Then I can enable that button when the next is pushed. It's not what I want, but it may have to do if nobody can suggest something better. I REALLY WANT "all the buttons disabled" for a time while the animated gifs and wav files are playing, then automatically re-enabled. It seems there is no way to check if an animated gif has reached it's last frame. I really don't want to put all the single frames into an array. Someone must have a better idea. Come on folks!

  6. #6
    NotTooOld is offline Hostage
    Join Date
    Apr 2013
    Location
    China
    Posts
    128
    Rep Power
    0

    Default Re: Muti Thread? Sleep()?? Timer?? none of these seem to work for me.

    Woo Hoo! I found an example of multi-threading that works! Now to incorporate it in my code.
    Java - Multithreading Programming Tutorial

    Create a Class:
    Java Code:
    // Create a new thread in some Class //////////////////////
    //
    class NewThread implements Runnable {
       Thread t;
       NewThread() {
          // Create a new, second thread
          t = new Thread(this, "Demo Thread");
          System.out.println("Child thread: " + t);
          t.start(); // Start the thread
       }
       
       // This is the entry point for the second thread.
       public void run() {
          try {
             for(int i = 5; i > 0; i--) {
                System.out.println("Child Thread: " + i);
                // Let the thread sleep for a while.
                Thread.sleep(500);
             }
         } catch (InterruptedException e) {
             System.out.println("Child interrupted.");
         }
         System.out.println("Exiting child thread.");
       }
    }
    Then include this in the code with your "main" method. (Must be in another file, not the one with the part above.)

    Java Code:
    public class ThreadDemo {
       public static void main(String args[]) {
          new NewThread(); // create a new thread
          try {
             for(int i = 5; i > 0; i--) {
               System.out.println("Main Thread: " + i);
               Thread.sleep(1000);
             }
          } catch (InterruptedException e) {
             System.out.println("Main thread interrupted.");
          }
          System.out.println("Main thread exiting.");
       }
    }
    I guess the other examples I found on the net probably also work, but were just too complex for "me" to get them to work. We'll soon see if I can get this to work in my project.
    Last edited by NotTooOld; 04-08-2013 at 05:20 AM.

  7. #7
    NotTooOld is offline Hostage
    Join Date
    Apr 2013
    Location
    China
    Posts
    128
    Rep Power
    0

    Default Re: Muti Thread? Sleep()?? Timer?? none of these seem to work for me.

    Ok, I have a second Thread running independent of the Thread drawing my JFrame. I get no errors with this code, but the calls to [DisableKeys()] and [EnableKeys()] are not working. How do I get this class to use the methods in my JFrame class? Do I need to "cast" those method calls?? What's missing here? I can get AlphaTimer to change values in AlphaPlay... I think I'm close.
    I call the code below at the end of the method I use to change gifs and wav files. Gifs change, are animated properly, wav file plays, and this file outputs:
    Demo Thread is running.
    i = 3
    Exiting Demo Thread.


    Java Code:
    	
    public class AlphaTimer extends AlphaPlay implements Runnable {
    
    	// Create a new thread.
    	Thread t;
    	
    	AlphaTimer() {
    	      t = new Thread(this, "Demo Thread");
    	      t.start(); // Start the thread
    	}
    	public void run() {
    		System.out.println("Demo Thread is running.");
    		try {
    			int i = 1;
    			if (i == 1){
    			DisableKeys();
    	        Thread.sleep(6000);
    	        i++;
    			}
    			if (i == 2){
    	        EnableKeys();
    	        i++;
    			}
    			System.out.println("i = " + Integer.toString(i));
    		} 
    		catch (InterruptedException e) {
    	    	 e.printStackTrace();
    	    }
    	    System.out.println("Exiting Demo Thread.");
    	   }
    }
    Here are the two methods I call on this thread.
    Java Code:
    	public static void DisableKeys() {
    		for(int i = 0; i <= 26; i++){
    			allButtons[i].setEnabled(false);		
    		}		
    	}
    	public static void EnableKeys() {
    		for(int i = 0; i <= 26; i++){
    		allButtons[i].setEnabled(true);
    		}
    	}
    }
    Last edited by NotTooOld; 04-08-2013 at 08:19 AM.

  8. #8
    NotTooOld is offline Hostage
    Join Date
    Apr 2013
    Location
    China
    Posts
    128
    Rep Power
    0

    Default Re: Muti Thread? Sleep()?? Timer?? none of these seem to work for me.

    I patched together a "timer." I recorded a "silent" wave file and use ...

    Java Code:
    public void update(LineEvent evt){
        	if (evt.getType()== LineEvent.Type.START){
        		DisableKeys();
           	}
        	if (evt.getType()== LineEvent.Type.STOP){
        		EnableKeys();
    Just make the wav file the right length. I made 5 and use their length in their names.
    that code to turn the buttons on and off.
    I know, it's pretty "hokie," but it gets me past one more hurdle.

Similar Threads

  1. Replies: 1
    Last Post: 09-24-2012, 07:01 PM
  2. change thread.sleep() to timer.
    By MaximumDolphin in forum Java Applets
    Replies: 16
    Last Post: 04-15-2011, 12:55 AM
  3. Difference between Thread.yield() and Thread.sleep() methods
    By Nageswara Rao Mothukuri in forum New To Java
    Replies: 12
    Last Post: 07-30-2010, 05:37 PM
  4. how to reduce the thread sleep time and wake up the thread
    By baktha.thalapathy in forum Threads and Synchronization
    Replies: 2
    Last Post: 06-24-2010, 07:36 PM
  5. How to use the sleep and thread?
    By jiuhu in forum Java Applets
    Replies: 4
    Last Post: 08-07-2007, 02:56 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •