Multithreaded Swing and a "Cancel Button"

I have a Swing-based app that runs some lengthy JDBC queries. Currently when the user hits the "Run Query" button a small dialog pops up to say that the process is running, please wait, etc. I'd like to add a working Cancel button to that dialog that will allow the user to stop that query before it finnishes.
From what I've been able to learn so far it seems I should use one of the SwingUtilities methods such as invokeAndWait or invokeLater. I'm not sure which one would be more appropriate for my situation though.
I'm also having trouble thinking of an elegant way (or not-so elegant if that's the only way) to have the cancel button event communicate with the DB Query thread to let it know that the process should be stopped. Detailed explanations or examples would be welcome.
Mike

You will not need to use the SwingUtilities methods. Those are when you want to update the GUI from a different thread. In your case, you want to update a class running in a non-gui thread from the GUI thread. Not a problem.
You will want to create a Runnable class that runs your query. Run that class on another thread when the query is executed. There will need to be some public 'cancel' method in that class that can be called when you want that object to cancel whatever operation it is doing. Simply call that 'cancel' method from your dialog button's action when the user hits the cancel button.
Now, how your query class handles the cancel method is the main problem. The api way of doing this would be to call the Statement.cancel() method on the statement object that is performing the query. But how (or if) that method works depends on the jdbc driver & database, hopefully yours supports it. :-)

Similar Messages

  • Drag drop and ProgressBar cancel button

    Hi,
    I have a class that extends CDragDropTargetFlavorHelper, during ProcessDragDropCommand I want to show a ProgressBar (the code that does this is actually in another, model only, plugin - might be significant), however, though the progress bar shows the cancel button doesn't.  Unless I delay the processing until after the drop is complete by scheduling the command - if I either process the command or schedule and process scheduled commands the cancel button doesn't show.
    Scheduling the command gives a bit of a delay to the user (even with highest priority) and also no ability to feedback 'drop failed'.  So I'd like to:
    - preferably get the cancel button to show without scheduling the command
    - know immediately when a drop has been completed and process scheduled commands.
    Thanks in advance
    Ian

    Thanks Ned,
    I have since been continuing to research this and it would seem that implementing the HitTest could be the way to go. If anyone has any experience or advice to support this I would be grateful.
    Regards
    Chris

  • JOptionPane.showInputDialog and the cancel button

    so i'm using a JOptionPane.showInputDialog, and everything works except when i click the cancel button to exit the window, it gives me an error.
    how can i remedy this?
    here's a section of my code: (a is an array, as is b)
    firstWord = JOptionPane.showInputDialog
    ("What company's sloagan is/was: "+a[count]+"?");
    if(firstWord.equalsIgnoreCase(b[count]))
    JOptionPane.showMessageDialog (null,
    "Thats Right, the company was "+b[count]+".");
    count++;
    int YesNo = JOptionPane.showConfirmDialog (null,
    "Do you want to play again?", "Choose One", JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
    if(YesNo==1) //this should exit out if you click no
    System.exit (0);
    if(count==10)
    JOptionPane.showMessageDialog(null,
    "Game Over. You Won.");
    System.exit (0);
    else
    JOptionPane.showMessageDialog (null,
    "Sorry, you aren't that smart. Guess again.");
    }]

    1- Seems like you misstyped your code tags...
    2- When you say: "it gives me an error", please provide details (e.g. stack trace)
    3- Read the API doc, it says: showInputDialog returns user's input, or null meaning the user canceled the input.
    So firstWord.equalsIgnoreCase(b[count]) will throw a NullPointerException in that case.
    You might check for null value.
    Note:str1.equals(str2) will throw a NullPointerException when str1 is null, but str2 can be null without a NullPointerException being thrown:String str1 = null;
    String str2 = "toto";
    System.out.println(str1.equals(str2)); // NullPointerException
    System.out.println(str2.equals(str1)); // ok (prints false)

  • Popup- ok and cancel button

    Hello,
    The popup 'X' has nested view 'Y' and Ok, Cancel buttons. Nested View 'Y' has a start point, a Data service, a table with single column 'Z' and a out-port (configured to event Select), from the out-port, close pop-up endpoint is connected which is mapped to store the value of column 'Z'.  The value of column Z, should be send out only on the click of OK button of the pop-up and not when Cancel is clicked, is there a way to validate that? At this moment, it is sent regardless of which button is clicked.
    Thanks much,
    Dharmi

    Hi Kobi,
    I understood what you said but how do you do "that can be set to TRUE in the popup OK button." ?? The popup at [design time|http://img145.imageshack.us/img145/8789/popupdesigntimeks2.jpg] and [layout|http://img371.imageshack.us/img371/750/popuplayoutgs4.jpg].
    If it is a normal form which has button you can store anything with that to data store, here how would I link that "OK" (close window) action of popup?
    Best regards,
    Dharmi

  • ADF Dialog Framework Cancel Button

    Hi all,
    We're experiencing, in multiple applications, a problem with a Cancel button (immediate="true") on a page launched by the dialog framework. While the value does not change in the model layer (saving to the database confirms this), it does seem to appear in the application UI, even after clicking the cancel button, until you post data.
    Details follow:
    This code is all JHS-generated, but we've spoken to Steven Davelaar, and he's pretty sure it's not a JHS problem. I certainly can't see anything obviously wrong with the code.
    Here's the component that launches the dialog, minus attributes like "rows" and "columns":
    <af:panelLabelAndMessage label="MIS Notes: "
        id="RpReportDocHeaderVwMisNotesLabel">
        <af:inputText id="SomeAttr" value="#{bindings.SomeAttr.inputValue}"
            required="#{bindings.SomeAttr.mandatory}"
            simple="true" partialTriggers="SomeAttrEditorLink"
            binding="#{SomeAttrEditorItem.editorItem}">
        </af:inputText> 
        <f:facet name="end">
            <af:commandLink id="SomeAttrEditorLink"
                action="dialog:editor" immediate="true" useWindow="true"                           
                partialSubmit="true" windowHeight="320" windowWidth="670"
                returnListener="#{SomeAttrEditorItem.returnedFromEditor}"
                launchListener="#{SomeAttrEditorItem.launchEditor}">
                <af:objectImage source="/jheadstart/images/editor.gif"/>
            </af:commandLink>
        </f:facet>
    </af:panelLabelAndMessage />The editor window, minus layout, form, etc. elements, is as follows:
    <af:inputText rows="10" columns="100"
        value="#{processScope.editorValue}"
        maximumLength=
            "#{processScope.editorMaxLength==0 ? null : processScope.editorMaxLength}" />
    <af:panelButtonBar>
        <af:commandButton text="Cancel" immediate="true">
            <af:returnActionListener/>
        </af:commandButton>
        <af:commandButton text="OK">
            <af:returnActionListener value="#{processScope.editorValue}"/>
        </af:commandButton>
    </af:panelButtonBar>Now, SomeAttrEditorItem is a managed bean of type oracle.jheadstart.controller.jsf.bean.EditorItemBean, so it's JHS code, but nothing about it should really matter if the returnActionListener for the Cancel button doesn't contain a value and is immediate, should it?
    Any help much appreciated. Thanks much,
    Avrom

    Thanks, Frank. This looks like a JHS bug (albeit one we can work around by writing our own template)--JHS should probably not be generating code that leaves cancelled changes in place. I'll notify them on their forum.
    [Edit:] Actually, there's something I don't understand about the instructions. In a case like this, I really only want to undo changes to a particular attribute--whatever attribute the dialog changed. And ideally, I don't want to refresh to the last pre-commit point; I want to just discard the changes that were made by this particular dialog. So I don't really think Row.refresh() is going to work here.
    Now, I could do something like this: In the launch listener, store the relevant attribute in some transient location, and on return, refresh it. But that seems overly complicated; isn't there a way to just not submit a dialog's values upon returning to the original form, or, at least, to prevent them from updating the model?
    Message was edited by:
    Avrom
    [Further edit:] Wait, no, there's something even stranger going on here. Note that the text input in the dialog isn't bound to "#{bindings.SomeAttr.inputValue}"; it's bound to "#{processScope.editorValue}". And the cancel button doesn't even have a returnActionListener! So how is the value getting passed back to the original form?
    Message was edited by:
    Avrom

  • Processing Page with cancel button.

    Hi,
    I have implement Processing Page but client wants to have cancel button to cancel the process.
    Can anyone give suggestions how to implement this?
    SC

    My requirement is that i have a custom base page with submit button. When user clicks on submit button it would start long running process
    And I should show a dialog page with clock saying process in progress message and a cancel button. User should be able to stop the process by clicking cancel button and back to base page. OAF gives the processing page that i want but without cancel button.
    I try to add cancel button on the processing page programmatically but while it is processing and when i click on cancel button i cannot capture the event.
    how to add cancel button on it and capture event? Is this correct approach?
    Can any body could suggest the best approach and solution?
    Thanks
    SC

  • How can I unsubscribe while the cancel button is u...

    There is no next payment for my subscription and the cancel button is missed. Is that mean the subscription will not automatically subscribe the next one until I confirm?

    I find that I will not have need of a skype account.  My free month is expired 09/22/14. I am a bit confused on how to do this on the web page - I do not see a"call phone tab" to go on to subscription settings.   So sorry.  I need your help with this.  Please cancel any renewal that may  be pending on my account.  Notify me with a confirmation on the cancellation.. Thank you very much.
    [Name redacted for privacy.]

  • Trapping Apply Cancel Button Press

    Hi,
    I have an extension page to process client specific data that contains an Apply and a Cancel button. When the user presses the Apply button I need to trigger the commit. However, the code never gets triggered.
    In my processFormRequest() I have the following statement:
    if (pageContext.getParameter("Apply") != null)
    // do commit.....
    Under debugger I can see jDeveloper action the if statement but it never steps into the commit.The Button that triggers the processFormRequest is called "Apply" (in its ID) and it has a type of submitButton.
    Anybody come across this one before ?
    Thanks,
    Paul

    Ummm,
    solved this one myself (embarrased silence...)
    I had the ActionType set to 'fireAction' on the apply button, rather than to 'none' as it should be...
    Not sure why, as I dont recall setting it but still.
    Problem solved.
    Have to go and look up what fireASction is supposed to do...:-)

  • Mapping enter and esc to ok and cancel buttons

    Hi,
    Does java's fine API offer any method of mapping Enter and ESC to OK and Cancel buttons in a customized JDialog?
    The current way I'm doing it is through a brute force of adding a KeyListener to every component in the dialog box (in an automated way), is there another way?
    Any suggestions would be appreciated.

    Uh oh, should I be scared because he knows more about
    Swing than just about anyone?
    Yes. Because if you really get stuck then he won't help you and then you are doomed.
    If anybody was rude it was him, and if anybody is an
    idiot it's you. See how easy it is to make claims
    without providing any reasons or rationale?Reasons and rationale have been provided but I guess you didn't grasp them the first go around so here goes.
    1) You were impatient
    You waited 30 minutes before whining and bumping. That is impatient. Nobody is being paid to deliver answers to you.
    2) You posted in the wrong forum.
    This is not the Swing forum is it? No it is not.
    3) You should learn to search
    If you had searched for even up to 15 minutes (and you wouldn't have needed this long) then you would have had your answer in half the time. Searching saves YOU time.
    4) You were rude
    When the facts (and please note the use of the word "fact" not personal opinion) above were pointed out to you then you were rude.
    Finally the "you are an idiot" problem. I will give you this is the most subjective of the lot although given that you cannot dispute ANY of the above facts (although you seem to be trying and that's helping to make the case that you're quite the idiot) that's really not saying much.
    However, it seems to me that if Person A wants the assistance of Person B (who is a valuable resource of information for person A and others) it does not seem wise for Person A to be rude to person B. So in the case of Person A who is rude to Person B who they are relying on as a free resource we can make the assertion that Person A is an idiot.
    In case you couldn't follow that you are Person A.

  • How to handle the "cancel" button and "close" icon of a popup ?

    Hi,
    I have a popup with "cancel button" and "close icon"(on the top right corner of the popup), I want the same operations to be performed on clicking of any of these two components.
    Is there a way to handle such situation ?
    I read about 2 cases to look into this but they didn't work too well for me.
    1. I read about the "popcancellistener" but that listener is called whenever the popup closes, so suppose I have an "ok button" on the popup to create a record, after the record is created, the popup closes and goes into the "popcancellistener", now the question is "how do we know if it came there because of the 'ok button' or 'some other event'".
    2. I even checked the "DialogListener", now I'm able to distinguish between the 'OK' and 'CANCEL' button in the dialoglistener using the "Dialog.Outcome.ok/cancel", but when a user clicks on the close icon, we do not enter the "DialogListener" at all, so in this case "how do we handle the close icon click event"
    Do let me know if you need any more information from my side.
    Thanks for the help in advance.

    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){
    }

  • Using Tiscali Webmail with Firefox 6. If I try and delete an email the Ok and Cancel buttons are disabled and nothing happens, have to use F5 to take me back. IE8 works so is this a compatibility issue?

    Using Tiscali Webmail with Firefox 6. If I try and delete an email the Ok and Cancel buttons are disabled and nothing happens, have to use F5 to take me back. IE8 works so is this a compatibility issue?

    It appears OP solved the problem: [/questions/874744]

  • Creating a dialog box with OK and Cancel buttons without OADialogPage

    Hi Experts,
    i want to create a dialog box for Delete Confirmation means after clicking on delete it should pop up a small dialog box with OK/Cancel buttons
    and need code for the same to handle the buttons.
    i have created with OADialogPage but its showing in a complete page but i want to show those buttons in a small box.
    Plz help.
    THANKS IN ADVANCE.
    Thanks
    Raja.

    Hi,
    I have not tried using javascript in destination URI as suggested by Mukul.
    I have tried the below code for opening a page as dialog box.
    You can try it for your requirement by creating a dialog page of your own, say XXDialogPage (with OK and Cancel button)
    StringBuffer l_buffer = new StringBuffer();
    l_buffer.append("javascript:mywin = openWindow(top, '");
    String url = "/OA_HTML/OA.jsp?page=/xx/oracle/apps/fnd/dialog/webui/OADialogPG";
    OAUrl popupUrl = new OAUrl(url, OAWebBeanConstants.ADD_BREAD_CRUMB_SAVE );
    String strUrl = popupUrl.createURL(pageContext);
    l_buffer.append(strUrl.toString());
    l_buffer.append("', 'lovWindow', {width:500, height:500},false,'dialog',null);");
    pageContext.putJavaScriptFunction("SomeName",l_buffer.toString());
    In dialog page's controller, you can forward it to the page onc ethe user selects OK or Cancel.
    Pass the selected value back to the main page and further you can use it for deleting.
    Regards.

  • Reg: save exit and cancel buttons

    Hi,
    In normal report programs when we enable the back , exit and cancel buttons they work fine without writing any code.but its not in the case of Module pool why?
    In thr normal reports where does the code come from?
    regards
    prasanth

    Hi....
    Module pool programs is nothing but screen flow + reports...
    Here we designing the screens....
    So we hav to to give every functionality.. for all buttons and menu items of the appeared screen...
    Where as in reports...,
    We are just using the standard screen (sellection screen and list output screen ) s mostly...,
    Here also some times we hav to go for created screens.. nothing but.... interactive reports...,
    There we need to give again all those functionalities...
    And..,
    To see the BACK button logic and other logics in the reports...,
    Ex: PAI event of SAPLWBABAP program..., 
    You can find that name with...
    By giving /H and enter before ur action...
    Thanks,
    Naveen.I

  • How I can internatiolization OK and Cancel buttons confirmDialog?

    private void clickButton() {
              int response = JOptionPane.showConfirmDialog(this, resBundle.getString("Confirmation_text_itroduction"),
    resBundle.getString("Confirmation_title"), JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE);
    if (response == JOptionPane.OK_OPTION) {
                   System.out.println("OK button clicked");
              } else if (response == JOptionPane.CANCEL_OPTION) {
                   System.out.println("Cancel button clicked");
    As you can see I internatiolization the title of confirm dialog and text (use object resBundle). OK!
    But how I can internatiolization OK and Cancel buttons is this confitm dialog?

    OK, I can internatiolization buttons "OK" and "Cancel" in confirm dialog:
    private void clickTestKindButton(String message) {
              Object[] options = { resBundle.getString("OK"),
                        resBundle.getString("Cancel") };
              int response = JOptionPane.showOptionDialog(this, message, resBundle
                        .getString("Confirmation_title"), JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
              if (response == JOptionPane.OK_OPTION) {
                   new IntroductionTest();
              } else if (response == JOptionPane.CANCEL_OPTION) {
                   System.out.println("Cancel button clicked");
         }It's work OK!
    But how I can internatiolization buttons "OK" and "Cancel" in the input dialog ?

  • Moving ok and cancel buttons

    Hi,
    When I do JOptionPane.showOptionDialog(...);
    Can anyone tell me how to make the ok and cancel buttons appear at the bottom right of the dialog instead of the bottom center.
    Thanks,
    Jim

    Sure, use another panel as a spacer thusly:
    | |
    | Other Panels |
    | |
    | Spacer | OK Can|<-position panel contains both panels
    Use BorderLayout for the entire dialog and set a position panel to be SOUTH (If you are using someother layout, add a full panel as a backdrop and move your Other panels into it using NORTH). Add the Spacer panel and 'OK/Cancel' panel to this using GridLayout (2 columns, 1 row).
    There is no restriction, other than memory size, to how many panels you use and their hierarchy.
    Robert Templeton

Maybe you are looking for