Link to home
Start Free TrialLog in
Avatar of HuwCrosweller
HuwCrosweller

asked on

Timer/Sleep?

I am loading several Web Pages up consecutively within a JEditorPane but I can't seem to get a timer or sleep function to work that will pause for a set time once the page has loaded before trying to load the next page.  Can anyone help me with this?
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

try{ Thread.sleep( 2000 ) ; } catch( InterruptedException e ) { }

I guess you've tried this tho...

can you show us some code?

And I don't want to sound like a bitch, but 20 points?

Easy is 50...  is this 2 * easier than easy?  It's got you stumped...

</rant> ;-)

(soz...I've got a cold, and no sleep == grumpy)
Avatar of HuwCrosweller
HuwCrosweller

ASKER


for (int i = startIndex; i <= endIndex; i++)
{
GoogleSearchResultElement element = resultElements[(i)];
                                   String title = element.getTitle();
                                   pagesTitle.add(title);
                                   String url = element.getURL();
                                   pagesURL.add(url);

                                   model.addElement(url);
                                   

                                   getThePage(url);
//                              pause();
//                                   JOptionPane.showMessageDialog(null, "Click for next Page", "Next Page", JOptionPane.ERROR_MESSAGE);
                              }

                         }
                         catch (GoogleSearchFault gsf)
                         {
                              JOptionPane.showMessageDialog(null, "An Error Occured When Searching", "Search Error", JOptionPane.ERROR_MESSAGE);
                         }
                    }
               }
          );

          URLList.addListSelectionListener(
               new ListSelectionListener() {
                    public void valueChanged(ListSelectionEvent URLSelect)
                    {
                         try
                         {
                              Runtime.getRuntime().exec("/usr/local/bin/netscape " + url);
                            }
                            catch(IOException ioe)
                            {
                                ioe.printStackTrace();
                            }
                    }
               }
          );

          SearchContainer.add(searchResultField, BorderLayout.NORTH);
         
          contentsArea = new JEditorPane();
          contentsArea.setEditable(false);

          SearchContainer.add(new JScrollPane(contentsArea), BorderLayout.CENTER);
          SearchContainer.add(new JScrollPane(URLList), BorderLayout.EAST);

          setSize(900,700);
          setVisible(true);


     }


     public void DelayLoadedPage() {
          timer = new Timer();
          timer.schedule(new DelayPage(), 30000);
     }


     private void getThePage(String URLWanted)
     {
          setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
         
          try {
               contentsArea.setPage(URLWanted);
          }
          catch (IOException ioException) {
               JOptionPane.showMessageDialog(this, "Error retrieving page", "Bad URL", JOptionPane.ERROR_MESSAGE);
          }
         
          DelayLoadedPage();
     }

     class DelayPage extends TimerTask {
          public void run() {
                    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                    timer.cancel();
          }
     }

     public void pause() {
          try {
               Thread.sleep(10000);
          } catch (InterruptedException ie) {
             }
     }

     public static void main(String args[])
     {
          SearchURL4 application = new SearchURL4();
          application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     }
}
public void DelayLoadedPage()
{
  timer = new Timer();
  timer.schedule(new DelayPage(), 30000);
  // dont forget
  timer.start() ;
}
PS:  Sorry again for my ranting...  I think I might go home from work...I really don't feel right...
I seem to get this error now?


SearchURL4.java:116: cannot resolve symbol
symbol  : method start  ()
location: class java.util.Timer
                timer.start();
                     ^
1 error
I seem to get this error now?


SearchURL4.java:116: cannot resolve symbol
symbol  : method start  ()
location: class java.util.Timer
                timer.start();
                     ^
1 error
I thought you were using javax.swing.Timer

Try the code I gave you there, with javax.swing.Timer instead, and this small change:


class DelayPage extends ActionListener
{
  public void actionPerformed(ActionEvent evt)
  {
    setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR ) ) ;
  }
}
Sorry get these errors now!

SearchURL4.java:126: no interface expected here
        class DelayPage extends ActionListener
                                ^
SearchURL4.java:107: cannot resolve symbol
symbol  : constructor Timer  ()
location: class javax.swing.Timer
                timer = new Timer();
                        ^
SearchURL4.java:108: cannot resolve symbol
symbol  : method schedule  (SearchURL4.DelayPage,int)
location: class javax.swing.Timer
                timer.schedule(new DelayPage(), 30000);
                     ^
3 errors
Try:

public void DelayLoadedPage()
{
  ActionListener delayPerformer = new ActionListener()
  {
    public void actionPerformed(ActionEvent evt)
    {
      // Do the thing you wanted after some time
    }
  };
 
  new javax.swing.Timer( 30000, delayPerformer ).start() ;
}

What JDK are you using?
PS:  In that example, comment out your DelayPage class
Well it complies but I still don't seem to get any delay when trying to load up the web pages
I've just realised that action listener won't work for what I'm doing. If I'm using java.util.Timer and java.util.TimerTask would I get the error that I had intially

SearchURL4.java:116: cannot resolve symbol
symbol  : method start  ()
location: class java.util.Timer
               timer.start();
                    ^
1 error

Sorry
yep

java.util.Timer does not have a start() method...

I SEE WHAT YOUR PROBLEM IS :-)

................

for (int i = startIndex; i <= endIndex; i++)
{
  GoogleSearchResultElement element = resultElements[(i)];
  String title = element.getTitle();
  pagesTitle.add(title);
  String url = element.getURL();
  pagesURL.add(url);

  model.addElement(url);
                                 
  getThePage(url);
}

................

private void getThePage(String URLWanted)
{
  setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) ) ;
  try
  {
    contentsArea.setPage(URLWanted);
  }
  catch (IOException ioException)
  {
    JOptionPane.showMessageDialog(this, "Error retrieving page", "Bad URL", JOptionPane.ERROR_MESSAGE);
  }
         
  // This is basically creating a new thread which is going off and waiting...whilst this one keeps running...
  //  DelayLoadedPage();
  Thread t = new Thread()
             {
                public void run()
                {
                   try{ this.sleep( 30000 ); } catch( InterruptedException e ) {}
                }
             } ;
  t.start() ;
  t.join() ;
}
Or...even better:

private void getThePage(String URLWanted)
{
 setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) ) ;
 try
 {
   contentsArea.setPage(URLWanted);

   // Make a new thread, which just sleeps
   Thread t = new Thread()
              {
                 public void run()
                 {
                    try{ this.sleep( 30000 ); } catch( InterruptedException e ) {}
                 }
              } ;

   // Start the new thread running
   t.start() ;

   // And wait for it to stop sleeping
   t.join() ;
 }
 catch (IOException ioException)
 {
   JOptionPane.showMessageDialog(this, "Error retrieving page", "Bad URL", JOptionPane.ERROR_MESSAGE);
 }
       
 // This was basically creating a new thread which is going off and waiting...whilst this one keeps running...
 //  DelayLoadedPage();
}
I'm off home to wrap up warm...I'll try to check back later to see if this worked :-)
From memory JEditorPane loads the page asynchronously so you may not know when the page has completed loading anyway.
Sorry just got this problem when I tried the second idea, any clues?


SearchURL7.java:125: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
  t.join() ;
   ^
1 error
try{ t.join() } catch( IterruptedException ex ) { }
So, putting it all together:

private void getThePage(String URLWanted)
{
  setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) ) ;
  try
  {
    contentsArea.setPage(URLWanted);

    // Make a new thread, which just sleeps
    Thread t = new Thread()
               {
                  public void run()
                  {
                     try{ this.sleep( 30000 ); } catch( InterruptedException e ) {}
                  }
               } ;

    // Start the new thread running
    t.start() ;

    // And wait for it to stop sleeping
    try{ t.join() } catch( InterruptedException ex ) { }
  }
  catch (IOException ioException)
  {
    JOptionPane.showMessageDialog(this, "Error retrieving page", "Bad URL", JOptionPane.ERROR_MESSAGE);
  }
       
  // This was basically creating a new thread which is going off and waiting...whilst this one keeps running...
  //  DelayLoadedPage();
}
Thanks for all your help so far but sorry to keep bothering you. The program works in the respect that I don't get any errors now, but it still doesn't seem to pause after each page is loaded.
Can you post your code as it is now?

Post the whole class if you can :-)
import com.google.soap.search.GoogleSearch;
import com.google.soap.search.GoogleSearchResult;
import com.google.soap.search.GoogleSearchFault;
import com.google.soap.search.GoogleSearchResultElement;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.util.Timer;
import java.util.TimerTask;
import java.io.IOException;

public class SearchURL7 extends JFrame {
      
      private Timer timer;
      private JTextField searchResultField;
      private JEditorPane contentsArea;
      private String searchTerm;
      private int endIndex, startIndex;
      private DefaultListModel model = new DefaultListModel();
      private JList URLList = new JList(model);
      public String url;
      Vector pagesTitle = new Vector();
      Vector pagesURL = new Vector();

      public SearchURL7 ()
      {
            super( "Search Powered By Google" );

            Container SearchContainer = getContentPane();

            searchResultField = new JTextField( "Search For" );
            searchResultField.addActionListener(
                  new ActionListener() {
                        public void actionPerformed(ActionEvent event)
                        {
                              searchTerm = event.getActionCommand();
                              try {
                                    GoogleSearch search = new GoogleSearch();
                  
                                    search.setKey("4c3N/fhQFHKOLXg7miI+6GzMlyVF2UhP");
                                    search.setQueryString(searchTerm);
                  
                                    GoogleSearchResult searchResult = search.doSearch();
                  
                                    GoogleSearchResultElement[] resultElements = searchResult.getResultElements();
                                    startIndex = searchResult.getStartIndex() -1;
                                    endIndex = searchResult.getEndIndex() - 1;
                              

                                    URLList.setVisibleRowCount(10);
                                    URLList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

                                    for (int i = startIndex; i <= endIndex; i++)
                                    {
                                          GoogleSearchResultElement element = resultElements[(i)];
                                          String title = element.getTitle();
                                          url = element.getURL();

                                          pagesTitle.add(title);
                                          pagesURL.add(url);

                                          model.addElement(title);

                                          getThePage(url);
                                    }

                              }
                              catch (GoogleSearchFault gsf)
                              {
                                    JOptionPane.showMessageDialog(null, "An Error Occured When Searching", "Search Error", JOptionPane.ERROR_MESSAGE);
                              }
                        }
                  }
            );

            URLList.addListSelectionListener(
                  new ListSelectionListener() {
                        public void valueChanged(ListSelectionEvent URLSelect)
                        {
                              int numSelected = URLList.getSelectedIndex();
                              try
                              {
                                    Runtime.getRuntime().exec("/usr/local/bin/netscape " + pagesURL.elementAt(numSelected));
                                }
                                catch(IOException ioe)
                                {
                                    ioe.printStackTrace();
                                }
                        }
                  }
            );

            SearchContainer.add(searchResultField, BorderLayout.NORTH);
            
            contentsArea = new JEditorPane();
            contentsArea.setEditable(false);

            SearchContainer.add(new JScrollPane(contentsArea), BorderLayout.CENTER);
            SearchContainer.add(new JScrollPane(URLList), BorderLayout.EAST);

            setSize(900,700);
            setVisible(true);


      }


      private void getThePage(String URLWanted)
      {
            setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) ) ;
            try
            {
                  contentsArea.setPage(URLWanted);

                  Thread t = new Thread()
                  {
                            public void run()
                            {
                              try{ this.sleep( 10000 ); } catch( InterruptedException e ) {}
                            }
                         };
              t.start();

try{ t.join(); } catch( InterruptedException ex ) { }

            }
            catch (IOException ioException)
            {
                  JOptionPane.showMessageDialog(this, "Error retrieving page", "Bad URL", JOptionPane.ERROR_MESSAGE);
            }

      }



      public static void main(String args[])
      {
            SearchURL7 application = new SearchURL7();
            application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }
}
Try:

import com.google.soap.search.GoogleSearch;
import com.google.soap.search.GoogleSearchResult;
import com.google.soap.search.GoogleSearchFault;
import com.google.soap.search.GoogleSearchResultElement;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.util.Timer;
import java.util.TimerTask;
import java.io.IOException;

public class SearchURL7 extends JFrame {

  private Timer timer;
  private JTextField searchResultField;
  private JEditorPane contentsArea;
  private String searchTerm;
  private int endIndex, startIndex;
  private DefaultListModel model = new DefaultListModel();
  private JList URLList = new JList(model);
  public String url;
  Vector pagesTitle = new Vector();
  Vector pagesURL = new Vector();

  public SearchURL7 ()
  {
    super( "Search Powered By Google" );

    Container SearchContainer = getContentPane();

    searchResultField = new JTextField( "Search For" );
    searchResultField.addActionListener( new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        searchTerm = event.getActionCommand();
        try
        {
          GoogleSearch search = new GoogleSearch();

          search.setKey("4c3N/fhQFHKOLXg7miI+6GzMlyVF2UhP");
          search.setQueryString(searchTerm);

          GoogleSearchResult searchResult = search.doSearch();

          GoogleSearchResultElement[] resultElements = searchResult.getResultElements();
          startIndex = searchResult.getStartIndex() -1;
          endIndex = searchResult.getEndIndex() - 1;


          URLList.setVisibleRowCount(10);
          URLList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

          for (int i = startIndex; i <= endIndex; i++)
          {
            GoogleSearchResultElement element = resultElements[(i)];
            String title = element.getTitle();
            url = element.getURL();

            pagesTitle.add(title);
            pagesURL.add(url);

            model.addElement(title);

            getThePage(url);
           
           
            Thread t = new Thread()
            {
              public void run()
              {
                try{ this.sleep( 10000 ); } catch( InterruptedException e ) {}
              }
            };
            t.start();
            System.out.println( "Waiting for Thread to finish" );
            try{ t.join(); } catch( InterruptedException ex ) { ex.printStackTrace() ; }
            System.out.println( "Finished...doing next item..." );
          }

        }
        catch (GoogleSearchFault gsf)
        {
          JOptionPane.showMessageDialog(null, "An Error Occured When Searching", "Search Error", JOptionPane.ERROR_MESSAGE);
        }
      }
    }
    );

    URLList.addListSelectionListener( new ListSelectionListener()
    {
      public void valueChanged(ListSelectionEvent URLSelect)
      {
        int numSelected = URLList.getSelectedIndex();
        try
        {
          Runtime.getRuntime().exec("/usr/local/bin/netscape " + pagesURL.elementAt(numSelected));
        }
        catch(IOException ioe)
        {
          ioe.printStackTrace();
        }
      }
    }
    );

    SearchContainer.add(searchResultField, BorderLayout.NORTH);

    contentsArea = new JEditorPane();
    contentsArea.setEditable(false);

    SearchContainer.add(new JScrollPane(contentsArea), BorderLayout.CENTER);
    SearchContainer.add(new JScrollPane(URLList), BorderLayout.EAST);

    setSize(900,700);
    setVisible(true);
  }

  private void getThePage(String URLWanted)
  {
    setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) ) ;
    try
    {
      contentsArea.setPage(URLWanted);
    }
    catch (IOException ioException)
    {
      JOptionPane.showMessageDialog(this, "Error retrieving page", "Bad URL", JOptionPane.ERROR_MESSAGE);
    }

  }

  public static void main(String args[])
  {
    SearchURL7 application = new SearchURL7();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}
It's hard for me to test it here, as I don't have the Google API...

:-/
AHHHHHHH!  I think I know what it is!

When you do JEditorPane.setPage( URL ), it loads the URL in a separate thread...  My guess is it is waiting, but it takes that same amount of time to actually load in the URL...

So what we need to do, is figure out a way to tell when setPage() is done, and wait for that...
ok it doesn't matter I'm sure that it's porbably just to do with the order that things are running.  Thanks alot for your help and suggestions anyway.
ASKER CERTIFIED SOLUTION
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Try:

import com.google.soap.search.GoogleSearch;
import com.google.soap.search.GoogleSearchResult;
import com.google.soap.search.GoogleSearchFault;
import com.google.soap.search.GoogleSearchResultElement;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.util.Timer;
import java.util.TimerTask;
import java.io.IOException;

import javax.swing.text.Document;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

public class SearchURL7 extends JFrame
{
  // We need this so the JEditorPane waits until it has finished loading :-)
  class MyEditorKit extends HTMLEditorKit
  {
    public Document createDefaultDocument()
    {
      Document doc = super.createDefaultDocument();
      ((HTMLDocument)doc).setAsynchronousLoadPriority(-1);
      return doc;
    }
  }
 
  private Timer timer;
  private JTextField searchResultField;
  private JEditorPane contentsArea;
  private String searchTerm;
  private int endIndex, startIndex;
  private DefaultListModel model = new DefaultListModel();
  private JList URLList = new JList(model);
  public String url;
  Vector pagesTitle = new Vector();
  Vector pagesURL = new Vector();

  public SearchURL7 ()
  {
    super( "Search Powered By Google" );

    Container SearchContainer = getContentPane();

    searchResultField = new JTextField( "Search For" );
    searchResultField.addActionListener( new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        searchTerm = event.getActionCommand();
        try
        {
          GoogleSearch search = new GoogleSearch();

          search.setKey("4c3N/fhQFHKOLXg7miI+6GzMlyVF2UhP");
          search.setQueryString(searchTerm);

          GoogleSearchResult searchResult = search.doSearch();

          GoogleSearchResultElement[] resultElements = searchResult.getResultElements();
          startIndex = searchResult.getStartIndex() -1;
          endIndex = searchResult.getEndIndex() - 1;


          URLList.setVisibleRowCount(10);
          URLList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

          for (int i = startIndex; i <= endIndex; i++)
          {
            GoogleSearchResultElement element = resultElements[(i)];
            String title = element.getTitle();
            url = element.getURL();

            pagesTitle.add(title);
            pagesURL.add(url);

            model.addElement(title);

            getThePage(url);
           
           
            Thread t = new Thread()
            {
              public void run()
              {
                try{ this.sleep( 10000 ); } catch( InterruptedException e ) {}
              }
            };
            t.start();
            System.out.println( "Waiting for Thread to finish" );
            try{ t.join(); } catch( InterruptedException ex ) { ex.printStackTrace() ; }
            System.out.println( "Finished...doing next item..." );
          }

        }
        catch (GoogleSearchFault gsf)
        {
          JOptionPane.showMessageDialog(null, "An Error Occured When Searching", "Search Error", JOptionPane.ERROR_MESSAGE);
        }
      }
    }
    );

    URLList.addListSelectionListener( new ListSelectionListener()
    {
      public void valueChanged(ListSelectionEvent URLSelect)
      {
        int numSelected = URLList.getSelectedIndex();
        try
        {
          Runtime.getRuntime().exec("/usr/local/bin/netscape " + pagesURL.elementAt(numSelected));
        }
        catch(IOException ioe)
        {
          ioe.printStackTrace();
        }
      }
    }
    );

    SearchContainer.add(searchResultField, BorderLayout.NORTH);

    contentsArea = new JEditorPane();
    contentsArea.setEditorKit( new MyEditorKit() ) ;
    contentsArea.setEditable(false);

    SearchContainer.add(new JScrollPane(contentsArea), BorderLayout.CENTER);
    SearchContainer.add(new JScrollPane(URLList), BorderLayout.EAST);

    setSize(900,700);
    setVisible(true);
  }

  private void getThePage(String URLWanted)
  {
    setCursor( Cursor.getPredefinedCursor( Cursor.WAIT_CURSOR ) ) ;
    try
    {
      contentsArea.setPage(URLWanted);
    }
    catch (IOException ioException)
    {
      JOptionPane.showMessageDialog(this, "Error retrieving page", "Bad URL", JOptionPane.ERROR_MESSAGE);
    }

  }

  public static void main(String args[])
  {
    SearchURL7 application = new SearchURL7();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}

THAT SHOULD WORK...

if it doesn't... I'm stumped :-(

Basically the new MyEditorKit class, tells the JEditorPane to load thing synchronosly (sp?), so it should work how you want...

Hope it helps :-)

Tim
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> Comment from objects 04/01/2003 04:06PM PST From memory JEditorPane loads the page asynchronously so you may not know when the page has completed loading anyway.

Oh yeah :-(

Sorry fella, you kinda got lost in huge source code dumps :-(

Apologetically Tim
dats ok :)
HuwCrosweller:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

- Split points between TimYates and objects

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

girionis
EE Cleanup Volunteer