• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 549
  • Last Modified:

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?
0
HuwCrosweller
Asked:
HuwCrosweller
  • 18
  • 10
  • 3
  • +2
2 Solutions
 
TimYatesCommented:
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)
0
 
HuwCroswellerAuthor Commented:

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);
     }
}
0
 
TimYatesCommented:
public void DelayLoadedPage()
{
  timer = new Timer();
  timer.schedule(new DelayPage(), 30000);
  // dont forget
  timer.start() ;
}
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
TimYatesCommented:
PS:  Sorry again for my ranting...  I think I might go home from work...I really don't feel right...
0
 
HuwCroswellerAuthor Commented:
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
0
 
HuwCroswellerAuthor Commented:
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
0
 
TimYatesCommented:
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 ) ) ;
  }
}
0
 
HuwCroswellerAuthor Commented:
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
0
 
TimYatesCommented:
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?
0
 
TimYatesCommented:
PS:  In that example, comment out your DelayPage class
0
 
HuwCroswellerAuthor Commented:
Well it complies but I still don't seem to get any delay when trying to load up the web pages
0
 
HuwCroswellerAuthor Commented:
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
0
 
TimYatesCommented:
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() ;
}
0
 
TimYatesCommented:
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();
}
0
 
TimYatesCommented:
I'm off home to wrap up warm...I'll try to check back later to see if this worked :-)
0
 
objectsCommented:
From memory JEditorPane loads the page asynchronously so you may not know when the page has completed loading anyway.
0
 
HuwCroswellerAuthor Commented:
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
0
 
TimYatesCommented:
try{ t.join() } catch( IterruptedException ex ) { }
0
 
TimYatesCommented:
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();
}
0
 
HuwCroswellerAuthor Commented:
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.
0
 
TimYatesCommented:
Can you post your code as it is now?

Post the whole class if you can :-)
0
 
HuwCroswellerAuthor Commented:
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);
      }
}
0
 
TimYatesCommented:
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);
  }
}
0
 
TimYatesCommented:
It's hard for me to test it here, as I don't have the Google API...

:-/
0
 
TimYatesCommented:
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...
0
 
HuwCroswellerAuthor Commented:
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.
0
 
TimYatesCommented:
One sec...

Think I've got it :-)
0
 
TimYatesCommented:
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
0
 
objectsCommented:
> When you do JEditorPane.setPage( URL ), it loads the URL in a separate thread

I mentioned that ages ago, and nonone listened to me :(

The above won't work because you are blocking the EDT, so your whole GUI will get blocked.
0
 
TimYatesCommented:
> 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
0
 
objectsCommented:
dats ok :)
0
 
CleanupPingCommented:
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.
0
 
girionisCommented:
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
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 18
  • 10
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now