Stopping a thread from "cancel" button

Hello all,
I have a problem trying to stop a thread. I have a class that hits database and retrieves lots of data. This retrieval can take a long time if lots of data, so I have a progress bar displayed. This progress bar has a cancel button. I am not sure how to link the cancel button to the thread so the thread can exit. See code below for example of whats going on:
public class MainApp {
  public void doWork() {
    ProgressBar pbar = new ProgressBar();
    pbar.show();
    DatabaseThread dbThread = new DatabaseThread();
    dbThread.run();
public class ProgressBar {
  // displays a progress bar with cancel button
public class DatabaseThread extends Thread {
  public void run() {
    // hit database
}So how am I to cancel the DatabaseThread class from the ProgressBar class. Thanks for all suggestions!

what i said is that you need to hava a reference to your thread ine the class that handle the progressBar.
and in your Thread class you create a method like setCanceled(boolean b)...
public MyThread extends Thread{
   private boolean canceled = false;
   public void setCanceled(boolean b){
      canceled = b;
   public void run(){
      while(!canceled){
        //do your stuff

Similar Messages

  • Stopping a thread from running

    Hai
         I am new to java. It would be helpful for me if someone helps me out in doing this.
         Actually in my program ,I should
    i. Find out whether a particular file exists in the given directory or not.
    ii. If the file doesn't exist, my program should wait for certain timeframe and check for the same file again.
    iii. If the program cannot find the required file within the timeout specified, my application should exit.
         I have done (i) and (ii) using threads. But in the case of (iii), I came to know that stop() method is depricated.
         I am providing my code for a better understanding. Could you please let me know, what would be the best way to stop the thread from running after the timeout is reached in my program?
    Thanx in advance
    import java.io.File;
    public class Fileexists implements Runnable
    static Thread t;
    public static void main(String[] args)
         System.out.println("creation of object");     
         FileExists test = new FileExists();
         t = new Thread(test);
         t.start();
    // run method
    public void run()
         File f = new File("searchfile.txt");
         boolean b = f.exists();
    System.out.println();
    if(b == false)
    System.out.println("Required file doesnot exists");
    try
         t.sleep(20000);
    catch (InterruptedException e)
         // TODO Auto-generated catch block
         e.printStackTrace();
              t.run();
    else
    System.out.println("Required file found");
    } // end of run()
    } // end of FileExists class

    Actually your use of threads is a difference which makes no difference. The JVM starts an initial thread and runs your main(), at the end of which you start a thread and return. So you've just replaced one thread with another. There's no parallel processing.
    The t.run() at the end of your run() method won't work. A particular Thread object can only run once. It will give you an IllegalStateException.
    I can't see how multi-threading will help you with this task at all, all you need is a simple loop with a Thread.sleep in it.
    If you really want to use a separate thread or Timer to implement a timeout (as an exercise) then use Thread.interrupt() to wind up a thread. The looping thread should test with Thread.interrupted() in it's loop condition, if it's in sleep() when interrupted an InterruptedException will be thrown which you should catch and allow to break the loop and let the thread terminate.
    So your loop structure looks like:
    try {
    while(!Thread.interrupted()) {
        ...  do your test
        Thread.sleep(.....);
      System.out.println("Thread terminated by detecting interrupted");
      } catch(InterruptedException ex)  {
         System.out.println("Thread interrupted from sleep");
    You can get the Thread for the main thread simply by storing Thread.currentThread() in a Thread reference.
    I'd suggest using a java.util.Timer to launch your time-out and leave the loop on the main thread started by the JVM.

  • Simple stop and go from a button

    HELP!
    I have an animate document with 6 buttons (made up of an image, and svg and text) all grouped to a DIV. I then have my timeline setup so that if a button is clicked the other 5 change opacity to 50%. The animation autoplay is turned off so nothing happens when the file loads, it just displays the six buttons.
    I have labels on the timeline that I'm trying to reference with a click action. However whatever I do nothing works when I preview the file in a browser.
    There also seems to be something missing in the code panel. This is what I have assigned to a button:
    // insert code for mouse click here
    // play the timeline from the given position (ms or label)
    sym.play(play);
    Should there not be more code below the // insert code for mouse click here text?
    Please help I have no idea what I'm doing wrong! would be willing to send you the files to take a look.
    Thanks
    Lee

    Joel,
    Thanks I have used what you have shown but it still does not work.
    I have uploaded the fielbase as a zip to:
    www.litchfieldmorris.co.uk/Homepage_Anim.zip
    The file is 1.6Mb
    I would welcome you expertise and look at what I have produced and why it does not work.
    The functionality I would like is when a user moves the mouse over (and if possible their finger on a tablet) say the Resources 'pebble' that the other five pebbles are set to 50% opacity. Then on click / press it would redirect to a url.
    Would you be willing to take a look at what I have so far and advise on the best solution?
    Thanks so much in advance.
    Regards
    Lee Tempest

  • Stop current thread

    I have got a Thread (made from swing thread).
    In the run() method i create a frame with a button that has an "actionperformed" and I show this frame and I put a loop like "
    while(true){
    Thread.currentTread.sleep(1000);
    System.out.println("bip");
    But in the button action I try to kill this Thread.
    But, no one of the methods from Thread class "yield", "destroy", "interrupt" seems to work.
    QUESTION :
    ==> How can I do to kill a Thread when I have his name or when it is the current Thread.

    Right - your best option is to either make the thread null (thus removing the object and stopping the thread from running), which is a bit heavy handed. Be careful of this, especially if you'll be creating new instances all the time - creating and scheduling threads can be quite processor and time intensive.
    The other option is to have the while loop use a boolean variable, such that you can do something like
    // instnace variable:
    private boolean running = true;
    // now a method to modify it:
    public void setRunning(boolean run)
      running = run;
    //some more code in your class...
    // now the body of the run method:
    while(running)
      Thread.currentTread.sleep(1000);
      System.out.println("bip");
    }Thus, when someone calls yourObjectName.setRunning(false), the run() method will quit.
    All you have to do now is call yourObjectName.start() to make it run again.
    I can't think of any cleaner ways to do this, so if they're any Java Gurus out there, help me out here.
    So, do this if you want to stop a thread running; but if you really want to kill it, and not use it again, make the object null.
    Let me know if this works for you,
    Rich

  • How to stop the Flex application when user clicks on Cancel button from JS-confirm message?

    Hi All,
    I use the next code when a user clicks on a link:
    private function clickHandler():void
          ExternalInterface.call('confirm', 'Of course you want to go to the Adobe forums!');
          navigateToURL(new URLRequest('http://forums.adobe.com'), '_self');
    This will show up the javascript confimation box. But when the cancel-button is clicked, the user goes straightly to http://forums.adobe.com...
    How to stop Flex performing the next code when a user clicks on the Cancel button?
    Or, how to catch which button is clicked by a user in Flex?
    Thanks!

    I agree with Mr. Hall that using mx.controls.Alert in Flex may be a better route.
    Show the Alert like this:
    // show an alert with a question and yes and no choices
    Alert.show( "Would you like to go to the Adobe Forums?", "Question",
         Alert.YES | Alert.NO, this, closeHandler, null, Alert.YES );
    Then handle the response in the closeHandler() function:
    protected function closeHandler( closeEvent:CloseEvent ):void
    if( event.detail == Alert.YES )
         navigateToURL( new URLRequest('http://forums.adobe.com'), '_self' );
    else if( event.detail == Alert.NO )
         // they chose no
    The following documentation on Alerts may be helpful:
    http://www.flexafterdark.com/docs/ActionScript-Alert
    Let me know if that helps...
    Ben Edwards

  • How can I stop a JFrame from closing when clicking the close button.

    I need to display a dialog when a user attempts to close my app, giving them the option to close, minimize or cancel. How can I stop the form from closing after the user makes his selection? I have the folllowing code, but my form still closes after selecting an option:
    private void formWindowClosing(java.awt.event.WindowEvent evt) {                                  
            //An array of Strings to be used a buttons in a JOptionDialog
            String[] options = {"Close", "Minimize", "Cancel"};
            //Determines what the user wants to do
            int result = JOptionPane.showOptionDialog(null, "What to you want to do?  Close the application, minimize or cancel?", "Please select an option...", 0, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
           //Determines what to do, depending on the user's choice
            if (result == 0) {
                //Close the application
                System.exit(0);
            } else if (result == 1) {
                //Minimize the application
                this.setState(Frame.ICONIFIED);
        }Any help would be much appreciated!

    import java.awt.event.*;
    import javax.swing.*;
    public class test extends JFrame {
         public static void main( String[] args ) {
              new test();
         public test() {
              setSize( 200, 200 );
              //the next line makes the JFrame not close
              setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE );
              //now add a listener that does the trick
              addWindowListener( new WindowAdapter() {
                        public void windowClosing( WindowEvent e ) {
                             //ask the user and do whatever you wish
              setVisible( true );
    }

  • Stop a script process with a "Cancel" button

    Hi,
    I display a progress bar with a "Cancel" button while the  script is running. I can stop the script by pressing the "Esc" key but I  would like to stop the script process with the "Cancel" button. What  kind of command/event can I add to the button for doing this ?
    Thanks

    -> Update All your Firefox Plugins
    * https://www.mozilla.org/en-US/plugincheck/
    * '''When Downloading Plugins Update setup files, Remove Checkmark from Downloading other Optional Softwares with your Plugins (e.g. Toolbars, McAfee, Google Chrome, etc.)'''
    * Restart Firefox
    Check and tell if its working.

  • "Cancel" button is clicked stop app activating

    Hi
    I found a hole in my script which lets the user when clicking "Cancel" from the
    authentication dialog have immediate access to the application "TEST".
    How do I when the "Cancel" button is clicked stop the above from happening and not let the application activate?
    try
    set my_Allow to {" ether 00:00:00:00:00:00 ", " ether 00:00:00:00:00:00 ", " ether 00:00:00:00:00:00 "}
    set myCompID to do shell script "ifconfig | grep ether"
    if my_Allow does not contain myCompID then
    display dialog "You do not have permission to have or use this application" buttons {"OK"}
    quit
    else
    set pass_me to "/Applications/TEST.app/"
    set app_POSIX to POSIX path of pass_me
    do shell script "/usr/bin/open " & quoted form of (app_POSIX) with administrator privileges
    end if
    end try
    cheers
    Budgie

    Sorry, forgot to mention that this is going in AS Studio, the "Cancel" button is on the
    "Authenticate" window, which pops up, not on the "display dialog "You do not have permission blah blah blah", also when the "Cancel" button is clicked it says: Apple Script Error -1708
    on will open theObject
    try
    set my_Allow to {" ether 00:00:00:00:00:00 ", " ether 00:00:00:00:00:00 ", " ether 00:00:00:00:00:00 "}
    set myCompID to do shell script "ifconfig | grep ether"
    if my_Allow does not contain myCompID then
    display dialog "You do not have permission to have or use this application" buttons {"OK"}
    quit
    else
    set pass_me to "/Applications/TEST.app/"
    set app_POSIX to POSIX path of pass_me
    do shell script "/usr/bin/open " & quoted form of (app_POSIX) with administrator privileges
    end if
    end try
    end will open
    Budgie

  • Stop the report from firing until the user clicks the Go button?

    Hi All,
    Is there a way to stop the report from firing until the user clicks the Go button? At the moment it is populating when I open the dashboard page. I found something online that said i could use the Page Options>Save Current Settings> For Others.. but even though i am signed in as an administrator i only see a For Me.. option. Also, even after setting this option i would like to be able to hit the 'Go' button to run the report and have it uncollapse the section. Is this possible?
    Thanks

    Thanks for the replies,
    In my report i am trying to constrain the report to todays data only. However the only prompt i have is for another column. If i place a filter on the date column with Year=0000 it will not change with the prompt selection and so will never return any results. Is there any other way?
    It seems wasteful to fire a request to the database onload of the page. Is there an option to only fire a request what the prompts are entered? I will be using a stored proc which needs parameters to run the request so it would be good to be able to set the report to not run until it has parameters entered
    Thanks

  • Delete From Table on Cancel Button.

    Hi,
    i am facing funny problem.
    i have created form with report page and i have implement send email option on Page so i am attach more document with email.if i attach document then it's going in DUMY_DOC_FILE table .
    i have create a process
    delete from DUMY_DOC_FILE .
    Process Point IS ON Submit -After Conmputation and Validation
    On Page No 6.if i press Cancel Button.This button is redirect on page No 4.My Code on Page no 6.
    page is redirect to 4 but doc don't delete from DUMY_DOC_FILE Table.
    How to delete Doc From Table If I press Cancel Button.
    Thanks
    Edited by: 805629 on Jan 13, 2011 5:25 AM
    Edited by: 805629 on Jan 13, 2011 11:49 PM
    Edited by: 805629 on Jan 14, 2011 12:43 AM

    <li>Change Cancel Button in page 6 so that it submits.
    <li>If u have conditions on that delete PLSQL process, make sure that it runs when CANCEL button is pressed also. If it is unconditional, let it be.
    <li>Add a branch for the Cancel button which redirect to page 4
    So effectivelly instead of *[CANCEL] -> [Redirect to page 4]* , it becomes *[CANCEL] -> [SUBMIT] -> [DELETE PROCESS] -> [Branch: redirect to page 4]*

  • How do I stop an app from waiting?  I have tried to reboot by holding the home key and power button to power down.  Also, I have tried to sync the apps from my laptop with no success.  Can you help?  Thanks.

    How do I stop an app from waiting?  I have tried to reboot by holding the home key and power button to power down.  The app is still grayed out and waiting so it cannot be deleted.  Also, I have tried to sync the apps from my laptop and tried downloading new appswith no success.  Can you help?  Thanks

    If there are multiple apps trying to download at once, only one can download at a time and the rest say "Waiting" until it is then their turn. Try this. Double tap the icon of the Waiting app, and it should resume the download.
    How to Solve the Problem of An iPad App Download Stuck on “Waiting”
    http://ipadacademy.com/2012/06/how-to-solve-the-problem-of-an-ipad-app-download- stuck-on-waiting
    How To Get Rid Of Your iPad App Download Frozen Problem
    http://www.sidelineapple.com/how-to-get-rid-of-your-ipad-app-download-frozen-pro blem-and-not-lose-years-of-your-life-video/
    iTunes: How to resume interrupted iTunes Store downloads
    http://support.apple.com/kb/ht1725
    Another thing to try - Turn the iPad Off & then back ON.
    If that doesn't work:
    •  Log out of your iTunes store account.  Go to Settings > Store > Sign Out Then press the Home button.
    • Then press and hold the Home and Sleep buttons simultaneously and don't release them when it brings up the Turn Off screen; keep holding them until the Apple logo appears.
    • After restart, the Waiting should be gone.
     Cheers, Tom

  • Choose From List Cancel Button Throws Exception

    Hi all,
    When I click the "Cancel" Button on my CFL, I get an error....
    EXCEPTION: Matrix__EBS_FRM_CRDCLM__64.OnAfterChooseFromList raised
    No matching records found (ODBC -2028)
    Any ideas???

    Hi
    in your choose from list  event add this  condition
    If Not pval.SelectedObjects Is Nothing Then
    'write your code in this if condition
    end if
    hope it will help u.
    Regards,
    Mithun.

  • Chrome://custombutton/content/button.js:302 how do I stop these scripts from happenning?

    How can I stop these 'scripts' from happening? There doesn't seem to be any rhyme or reason. It happens on various sites, times of day, number of tabs, ... I can't pick up what the important variables are.

    That is a problem with the Custom Button extension.
    *https://support.mozilla.com/kb/Troubleshooting+extensions+and+themes

  • How to enable the "Cancel button" so you can stop a report while loading ...

    I have seen that some reports have a Cancel button located just below "the loading ..".
    How can I enable that button in MS Reporting service 2005?

    The following mechanism responds to any of the following events: <Esc> key, Close icon ('x'), Cancel button
    JavaScript part:
    function popupClosedListener(event){
                  var source = event.getSource();
                  var popupId = source.getClientId();
                  var params = {};
                  params['popupId'] = popupId;
                  var type = "serverPopupClosed";
                  var immediate = true;
                  AdfCustomEvent.queue(source, type, params, immediate);
    }JSF part:
             <af:popup ....>
                  <af:clientListener method="popupClosedListener"
                                           type="popupClosed"/>
                  <af:serverListener type="serverPopupClosed"
                                          method="#{myBean.serverPopupClosedMetod}"/>
            </af:popup>Finally, Java part:
    public void serverPopupClosedMetod(ClientEvent event){
    }

  • Exit using Cancel button from form preview.

    Hi
    I am looping into internal table and printing a smartform for every line.
    When I do the preview, and press back button, it takes me through the preview of all the items.
    Is there a way to come out of this preview.
    I am trying to use the cancel button in at user-command, but the program doesnot seem to recognise it.

    Hi,
    Regarding your qusetion about the preview.: In case you are calling the smartform inside a loop, the preview is going to get called. Incase you want just the 1st form to be shown, you could hardcode it in the program. Your logic could be:
    If its print preview, then exit in the 2nd pass of the internal table by checking the sy-tabix.
    Let us know if this suits your need. If it doesnt then throww more light on your question so that we cud suggest better!

Maybe you are looking for

  • I am not able to run a Windows Azure application

    I have a very strange issue. I am not able to run a windows azure application which has a WCF service and mschart in it. Following are the steps to reproduce the error: 1) Create a new windowsazureapplication with a blank asp.net webrole 2) Now add a

  • Load Images in Oracle Applications

    Hi friends, I'm trying to load/store a .jpg image. In client/server mode, there's no problem (forms 6i) using hits code in a button (i.e.): declare      dirname varchar2(255);      v_filename varchar2(255); begin      tool_env.getvar('IMAGE', dirname

  • Where to download weblogic

    hi, I want to download oracle weblogic , is it available at oracle edilvery link ;if yes then under which product pack will it be available. is it a licensed software or free ? and thanks in advance

  • Why is it that every time there's an update, my creative cloud always fails to install?

    This is the 4th time it is happening, and I have to go through the hassle of reinstalling and cleaning up. Does this happen because of a fault in my system or are we suppose to do this every update?

  • How do I alphabetize my menu list

    how do i alphabetize my bookmarks in menu list