Results 1 to 10 of 10
Like Tree2Likes
  • 2 Post By Fubarable

Thread: How to let a thread sleep while its respective Jpanel is not showing

  1. #1
    Reskaillev is offline Member
    Join Date
    Jul 2011
    Posts
    53
    Rep Power
    0

    Default How to let a thread sleep while its respective Jpanel is not showing

    I have a JApplet that makes two JPanels in its initiation and I set CardLayout as my layoutmanager. I add these two panels to my cardlayout.
    In these JPanels I have a Jbutton component that swaps to the other panel (using a procedure called Swapcards).

    One of these JPanels is runnable and there's a thread running.

    Now I'd like the thread to sleep while i'm not looking at the panel that has the thread running..
    By looking I mean that the Jpanel is not displayed in the applet.
    How to do this, without doing this in the Swapcards procedure?

    So I'd like the thread to notice the fact that its respective JPanel is not showing and thus decides to go to sleep (et vice versa).

    thnx in advance,

    Reskaillev
    Last edited by Reskaillev; 09-04-2011 at 07:33 PM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,403
    Rep Power
    25

    Default Re: How to let a thread sleep while its respective Jpanel is not showing

    Now I'd like the thread to sleep while i'm not looking at the panel that has the thread running..
    What will cause the sleeping thread to exit sleep? Is this a wait, notify problem?
    Why execute the thread when you want it to sleep. Don't start the thread until you want it running.
    How many threads do you have running in the app? What is the purpose of having the different threads?

    Can you make a SSCCE to demonstrate the problem?

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How to let a thread sleep while its respective Jpanel is not showing

    Perhaps you want to add a listener of some sort to the class that has the swapCards method and listen for a call to this method that would change card state. You could do this by giving this class a SwingPropertyChangeSupport variable, and initialize it with 'this'. You would then give the class an addPropertyChangeListener(...) method and a removeProp...(...) method, and then fire the property change support from within the swapCards method.

  4. #4
    Reskaillev is offline Member
    Join Date
    Jul 2011
    Posts
    53
    Rep Power
    0

    Default Re: How to let a thread sleep while its respective Jpanel is not showing

    ok Norm here's a short, self contained, correct example (love the abbreviation!)

    So here's the JApplet:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    
    public class ExampleApplet extends JApplet {
    	
    	RunningPanel runningPanel1,runningPanel2;
    	final String FIRST = "1";
    	final String SECOND = "2";
    	private CardLayout cardsLayout = new CardLayout();
    	private JPanel cards = new JPanel(cardsLayout);
    	
    	public void init()
    	{
    		runningPanel1 = new RunningPanel(this,this.SECOND,0);
    		cards.add(runningPanel1, FIRST);
    		runningPanel2 = new RunningPanel(this,this.FIRST,200);
    		cards.add(runningPanel2, SECOND);
    		this.setSize(650, 400);
            this.add(cards, BorderLayout.CENTER);
    	}
    	
    	public void swapCards(String key) {
    		cardsLayout.show(cards, key);
    	}
    
    }
    And here is the RunningApplet class:

    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JPanel;
    
    
    public class RunningPanel extends JPanel implements Runnable,ActionListener {
    
    	Thread runner;
            ExampleApplet example;
            JButton button;
            int i,position;
            String buttonText;
    
    	public RunningPanel(ExampleApplet example, String buttonText, int position)
    	{
    		i=0;
                    this.buttonText=buttonText;
                    this.example= example;
                    this.position= position;
                    button = new JButton(buttonText);
                    button.addActionListener(this);
                    this.add(button);
                    button.setAlignmentX(CENTER_ALIGNMENT);
    		runner = new Thread(this);
    		runner.start(); 	
    	}
        
    	public void paintComponent(Graphics g)
    	{
    		g.setColor(Color.black);
    		g.fillRect(0, 0, getWidth(), getHeight());
    		g.setColor(Color.white);
    		g.drawString(String.valueOf(i), 200+position,200);
    	}
    	
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    		while(true)
    		{
                            i++;
                            repaint();
    			try
    			{	
    				Thread.sleep (20);
    			}
    		catch (InterruptedException ex)
    			{
    			
    			}
    		}
    	}
    
    	public void actionPerformed(ActionEvent e) {
    	         example.swapCards(buttonText);
    	}
    	
    }
    The RunningApplet class adds a button and a counter that automatically goes up. I create two RunningApplets called runningApplet1 and runningApplet2 and give the button the power to call the SwapCards procedure from the JApplet.

    Now as you can see when you run the JApplet:
    - The counter doesn't stop counting when I change my view to the other JPanel

    Why would this be a problem?
    - When I create multiple JPanels with long runners the JApplet tends to slow down and it ain't necessary for the threads to run since i'm not looking at them

    The question:
    - How do I stop the thread from running when the corresponding JPanel is not showing? This method shouldn't be in the thread (since the thread will still run then, checking if the JPanel is showing). Nor in my JApplet since I want to put everything inside my JPanel

    hope that clears things up+how to do this?

    Thank you for your time,

    Resk

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How to let a thread sleep while its respective Jpanel is not showing

    Quote Originally Posted by Reskaillev View Post
    Why would this be a problem?
    You have a while(true) loop, and nothing in the code will stop this.

    The question:
    - How do I stop the thread from running when the corresponding JPanel is not showing? This method shouldn't be in the thread (since the thread will still run then, checking if the JPanel is showing). Nor in my JApplet since I want to put everything inside my JPanel
    Instead of while (true), use a boolean variable, while (displayed), and then set that variable, again perhaps with a PropertyChangeListener (as I mentioned before, but you never responded to, so I'm not sure if I wasted my time, if you even read it).

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How to let a thread sleep while its respective Jpanel is not showing

    Actually no need for a PropertyChangeListener with your simple example since the code to swap is in the same class as the one that holds the RunningPanel variables. Instead use an if block in the while loop, and set it in the swap panels method. e.g.,

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.swing.*;
    
    public class ExampleApplet extends JApplet {
       final static private String FIRST = "1";
       final static private String SECOND = "2";
       final static private String THIRD = "3";
       final static private String[] PANEL_NAMES = { FIRST, SECOND, THIRD };
       private CardLayout cardsLayout = new CardLayout();
       private JPanel cards = new JPanel(cardsLayout);
       private Map<String, RunningPanel> runningPanelMap = new HashMap<String, RunningPanel>();
    
       public void init() {
          for (int i = 0; i < PANEL_NAMES.length; i++) {
             int buttonNameIndex = (i + 1) % PANEL_NAMES.length;
             RunningPanel runningPanel = new RunningPanel(this, PANEL_NAMES[buttonNameIndex],
                   i * 200);
             runningPanelMap.put(PANEL_NAMES[i], runningPanel);
             cards.add(runningPanel, PANEL_NAMES[i]);
          }
    
          runningPanelMap.get(PANEL_NAMES[0]).setDisplayed(true);
    
          this.setSize(650, 400);
          this.add(cards, BorderLayout.CENTER);
       }
    
       public void swapCards(String key) {
          cardsLayout.show(cards, key);
          for (RunningPanel runningPanel : runningPanelMap.values()) {
             runningPanel.setDisplayed(false);
          }
          runningPanelMap.get(key).setDisplayed(true);
       }
    
    }
    
    class RunningPanel extends JPanel implements Runnable, ActionListener {
       Thread runner;
       ExampleApplet example;
       JButton button;
       int i, position;
       String buttonText;
       private boolean displayed = false;
    
       public RunningPanel(ExampleApplet example, String buttonText, int position) {
          i = 0;
          this.buttonText = buttonText;
          this.example = example;
          this.position = position;
          button = new JButton(buttonText);
          button.addActionListener(this);
          this.add(button);
          button.setAlignmentX(CENTER_ALIGNMENT);
          runner = new Thread(this);
          runner.start();
       }
    
       public void setDisplayed(boolean displayed) {
          this.displayed = displayed;
       }
    
       public void paintComponent(Graphics g) {
          g.setColor(Color.black);
          g.fillRect(0, 0, getWidth(), getHeight());
          g.setColor(Color.white);
          g.drawString(String.valueOf(i), 200 + position, 200);
       }
    
       @Override
       public void run() {
          while (true) {
             if (displayed) {
                i++;
                repaint();
                try {
                   Thread.sleep(20);
                } catch (InterruptedException ex) {}
             }
          }
       }
    
       public void actionPerformed(ActionEvent e) {
          example.swapCards(buttonText);
       }
    
    }
    Norm and Reskaillev like this.

  7. #7
    Reskaillev is offline Member
    Join Date
    Jul 2011
    Posts
    53
    Rep Power
    0

    Default Re: How to let a thread sleep while its respective Jpanel is not showing

    Quote Originally Posted by Fubarable View Post
    (as I mentioned before, but you never responded to, so I'm not sure if I wasted my time, if you even read it).
    Why no sir! offcourse I read it! (though i'm totally alien to a PropertyChangeListener)

    Problem is that I didn't really understand your solution.
    so I change the "true" of the while loop to a boolean called "displayed".
    I then bound my PropertyChangeListener to the SwapCards procedure.

    Then change the boolean displayed of the JPanel I'm leaving to false,
    the boolean displayed of the JPanel I'm entering to true and start up the runner by calling runnerPanel2.runner.start()?

    Did I get that correctly? Why would I need removeprop?

    My apologies for aggrevating you,

    Resk

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: How to let a thread sleep while its respective Jpanel is not showing

    See my other reply above for more on your current problem.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,403
    Rep Power
    25

    Default Re: How to let a thread sleep while its respective Jpanel is not showing

    If you don't like empty spinning loops you could use wait/notify:
    Java Code:
       public void setDisplayed(boolean displayed) {
          this.displayed = displayed;
          if(displayed) {
            synchronized(this) {
               notify();       // tell run loop to start again
            }
          }
       } // end setDisplayed()
    
       @Override
       public void run() {
          while (true) {
             if (displayed) {
                i++;
                repaint();
                try {Thread.sleep(20);} catch (InterruptedException ex) {}
             }else{
                // Lets wait until told to start looping again
                synchronized(this) {
                  System.out.println(buttonText + " entering wait");
                  try{wait();}catch(Exception x){}
                  System.out.println(buttonText + " exited wait");
                }
             }
          } // end while(true)
       } // end run()

  10. #10
    Reskaillev is offline Member
    Join Date
    Jul 2011
    Posts
    53
    Rep Power
    0

    Default Re: How to let a thread sleep while its respective Jpanel is not showing

    Thnx a lot guys!! XD

Similar Threads

  1. 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
  2. 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
  3. thread.sleep
    By jc5 in forum CLDC and MIDP
    Replies: 0
    Last Post: 09-02-2009, 11:51 PM
  4. Can't get my thread to sleep!
    By jamesfrize in forum New To Java
    Replies: 2
    Last Post: 03-25-2008, 05:14 AM
  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
  •