Waiting for button click

Hi,
I'm trying to create a program in which the program does nothing until one of the buttons is pressed, then acts accordingly. The way the program works, though, it can't just be by using the ActionPerformed method.
Currently, I have a while() loop that cycles through until one of the buttons is pressed, which kicks it out of the loop and allows that button to be processed. The problem, however, is that when the program is run, the while() loop takes control over the program and doesn't allow any buttons to be clicked, therefore rendering the loop infinite.
Basically what I need is a way for the while() loop to still be running, but at the same time for the buttons to be rendered able to be clicked so that the loop can end.
Is this possible?
Thanks in advance.

You might want to post your code so we can see what's going on. I post my code here a lot. Just remember to post only the relevant parts, but if you feel that it's necessary to post the whole program, always put something like "Warning: long post" in the subject header.
You might want to put your buttons in an array, and for each button, attach an ActionListener to it. Then have an inner ButtonHandler class. Here's how I would do it:
for (i=0; i<buttonArray.length; i++)
  buttonArray.addActionListener(handler);
Then at the end of your code, that is between the end of main and the last closing curly brace, try this:
private class ButtonHandler implements ActionListener
  public void actionPerformed(ActionEvent e)
    buttonPressed = e.getActionCommand();
I hope this sheds some light.  I don't know exactly what your code looks like, but hopefully, I'm making a good shot in the dark.  I don't see any need in using a while loop.  Just give this a shot, and if you still have problems, feel free to post your code and let us look at it.  Hope this helps! :-)
Syster Tara

Similar Messages

  • How do you go to marker  when there is a wait for mouse click between the markers?

    I cant seem to get by the wait for mouse click, when using                          go to (marker)
    I have a game that I have 2 push buttons one is
    on mouseUp me
      go to frame 9
    end
    on mouseUp me
       go to frame  29
    end
    There is a wait to click in between these 2  frames and when I click on the  2nd button to go to frame 29  it stops at the wait to click?
    I have tried  all these below and cant get past the click to wait?????
    go
    go to frame
    go to marker
    _movie.go
    _movie.marker
    _nextMarker=

    Think this issue is resolved but to ensure the full answer is available, here it is.
    First, it's a bad idea to use the Tempo channel at all. You can use a script to do anything that you can do there. I have Lingo alternates to the Tempo channel at:
    http://www.deansdirectortutorials.com/Lingo/tempoLingo.htm
    (think I need to update this page though)
    So - DO NOT USE the Tempo Channel setting - Wait for Mouse Click or Key Press.
    The above setting creates a type of pause that interferes with other interactivity.
    Instead - use a 'Hold on Frame' behavior (from the Library Palette - Navigation category) or it could be written as:
    on exitFrame
    go the frame
    end
    Once you have the above behaviour in you desired frame, you can attach a sprite behaviour to your buttons / links. A good one to use is the ‘Jump to Marker Button’ behaviour in the Controls category of the Library Palette. You can attach this behavior to different sprites and just change the marker setting of the behavior, removing the need to have individual hard-coded scripts for each button.
    Next – DO NOT link to frame numbers. Always link to a marker. You may insert or remove frames. This would cause your incorrect links since the frame number would no longer the right point.
    Next – the following all do the same thing:
    go to frame “markername”
    go to “markername”
    go “markername”
    So, you can leave out ‘frame’ or even ‘to’ as they are not needed. I still use ‘go to’ as it feels more natural to me (just history).
    or you could use:
    _movie.go("dean")
    Don’t use
    go to marker “markername”
    I think that did work at some point but not anymore.
    marker can be used as follows:
    go marker (-1)
    Where -1 is the amount of markers back (could be forward as well).
    Well, that gives the detailed answer to your question.
    Dean

  • Custom JDialog, waiting for Button Press

    I want to create a custom dialog so i can do the following:
    Color yrColor = MyColorChooser().showDialog();
    I can create the dialog just fine but i cant get it to return a value
    on a button press.
    Here is my code:
    public class MyColorChooser extends JDialog implements ActionListener{
    public MyColorChooser(){
    super(Main.Frame, "Color Chooser", true);
    // Gui Stuff
    public Color showDialog(){
    setVisible(true);
    // ?? how do i have it wait for button press??
    return YourColor;
    public void actionPerformed(ActionEvent e) {
    if( e.getSource() == Button ){
    returnColor()
    public void returnColor(){
    Color YourColor;
    JButton Button = new JButton();
    }Im clueless when it comes to JDialogs.
    I know i am probably approaching this all wrong.
    I need guidance more in the approach rather than the code.
    If anyone has any suggestions id appreciate it.
    Thank you!

    Maybe this simple example can give you some ideas. Note how I make the dialog modal. This will halt the program flow until the dialog is dismissed.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SimpleTextInputDialog extends JDialog implements ActionListener {
        private JTextField  inputField;
        private JButton     okButton;
        private JButton     cancelButton;
        private String      value;
        private SimpleTextInputDialog() {
            setTitle("Enter a value");
            setModal(true);
            inputField = new JTextField(20);
            JPanel textPanel = new JPanel();
            textPanel.add(inputField);
            getContentPane().add(textPanel, BorderLayout.CENTER);
            okButton = new JButton("OK");
            okButton.addActionListener(this);
            cancelButton = new JButton("Cancel");
            cancelButton.addActionListener(this);
            JPanel buttonPanel = new JPanel(
                    new FlowLayout(FlowLayout.CENTER, 10, 10));
            buttonPanel.add(okButton);
            buttonPanel.add(cancelButton);
            getContentPane().add(buttonPanel, BorderLayout.SOUTH);
            pack();
            setLocationRelativeTo(null);
        public void actionPerformed(ActionEvent e) {
            if( e.getSource() == okButton ) {
                value = inputField.getText();
            dispose();
        public static String getValue() {
            SimpleTextInputDialog dlg = new SimpleTextInputDialog();
            dlg.setVisible(true);
            return dlg.value;
        public static void main(String[] args) {
            String value = SimpleTextInputDialog.getValue();
            System.out.println("Entered value: " + value);
    }And as always, you should study the tutorials:
    "How to Make Dialogs":
    http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html

  • Switching Frames (cardsLayout), doing something, waiting for button

    Hi,
    I am switching JFrames in my application and each frame is to call a specific function and then wait for a button click.
    so the code would be:
    function(){
            cardsLayout.show();
            doSomeCalculations();
            waitForButtonClick
            continueWithSomething //depending on which Button was clicked
    }My problem is, how to realize the waitForButtonClick?
    What would you suggest? I have heard about synchronize. Is this the way to go, or is there an easier/better way?
    Besides a while(notClicked) way ;-)
    Thanks!

    pir wrote:
    it is not that I do not want to learn Java. Please understand that Java is not with what I am earning my living, it is a tool for me, to make some task easier, which I would have otherwise have to do step by step by hand. I will never be as good as someone who spends his time with Java every day. I also have only a specific task to perform in a given time, so I need only specific information - which I am definitely willing to learn - and not all there is about Java and Swing.You must understand that at its core, your question is not about anything specific but rather it boils down to: "how to create an event driven program in Swing".
    The only reasonable answer to this is to send you to the Swing tutorials where, if you have the interest, ability, and inclination, you can learn the tools needed to do Swing and event programming. If you choose not to do this, no one in this forum can help you. Period.
    I hope this clarifies the situation enough, to allow someone to have a heart and point me in the right specific direction, even knowing that I might use this knowledge only once.And once again, I recommend that you hit the Sun Swing tutorials and start learning. Accept this and follow this recommendation and you will find success. If not, well,... it's your choice.
    Thank you in advance for any specific help.This is as specific as it's going to get at this stage. Much luck.

  • Wait for button press......

    I have a JButton with an action listener. What I want to happen is when
    the button is pressed and goes into the action performed part it should
    wait for the same button to be pressed again before it does anything.
    The problem is once it goes into the action performed part of the action
    listener the button cannot be pressed again until it leaves...
    Any ideas how this could be done?
    Thanks

    public void actionPerformed(ActionEvent e){
       Object o = e.getSource();
       //the button was pressed once
       if (o == button){
          if(  //count the number of times the button was pressed and then divide it by 2
              /*and if the remainder will be one*/){
             //do this;
          else{
             //this is what you do if there is no remainder meaning the number is divisible by 2
    }You should also try using mouse events.
    You can count the mouse clicks with it.
    Hope this helps you.

  • Technical help needed  for button click

    Hi All,
    Im new to abap, just  now started working in my first project. I need some help and start from you.
    In my webdynpro component FPM_OIF_COMPONENT  : CNR_VIEW, Participate button  is there,
    so by default u201CCreate Responseu201C button is grayed out. By clicking the participate button, I need to enable the create response button. For this requirement, I need to create a custom class with two static methods : setvalue and getvalue methods. In that methods I need to set the variable = X, if participate button is pressed. And when loading WDDOMODIFY VIEW method, I need to check the value of the variable, if the value is X, then create response button will be enabled.
    For this logic, Can you please frame some sample code.
    Or please guide me throug some materials.
    Please help me in this regard.
    Regards,
    Rani.
    Moderator message: moved from ABAP forums.
    Edited by: Thomas Zloch on Jun 29, 2011 11:14 PM

    Hi Rani,
    I understand you are new to ABAP basically the webdynpro questions are posted in webdynpro-ABAP, Forums going forward you should adapt the same practice to get a better response.
    As you said u201CCreate Responseu201C button  is already grayed out it must be already linked to attribute of type wdy_boolean
    check the "enable property" of the button.
    Coming to your question :
    In the "OnAction" event of Participate button write a method for example  get value
    "Make the attribute" linked to create response button as abap_true hence whenever participate button is pressed it
    will make your create response button enabled.
    Regards
    Bhanu Malik

  • Executing javascript code for button click

    in my application i have report page where i am displaying table data when i click a button it selects first row and returns it using htp.prn() now i m getting that record in jvascript now i want to execute this java script code when the button is clicked i tried using onClick attribute but it didn't work can anyone tell me how to do it?

    Hi,
    I think this is related to Application express, right ?
    You could post your question in Application Express forum
    Oracle Application Express (APEX)
    Also please give more detail about your issue. Post e.g. code (pl/sql & javascript) you try to use.
    Also if you setup sample about your problem to http://apex.oracle.com will help others to help you.
    Help us to help you =)
    Br, Jari

  • Wait for user input in middle of method

    I have a method in the middle of which I want to give the user a chance to click one of several Buttons. Here is the basic design of the method:
    Private Sub MyMethod()
    'Code before I need extra input
    'This is where I want to wait for the user to click a Button
    'This is where I will be using the results from the clicked Button
    'The waiting for input and using the results will happen multiple times inside a loop
    End Sub
    The code is in a loop, so exiting the method and putting the rest of the code in the Button handler would not be appropriate. How can I ask the user for input and then return that input to the method where I left? I seem to be tempted to use some kind of async
    method, but since the input will be coming from the user (not another method), that doesn't seem like it would be right (but I don't have a huge amount of experience with async, so I could be wrong about that). Can anybody help me? Thanks.
    Nathan Sokalski [email protected] http://www.nathansokalski.com/

    Hi Nathan,
    You're on the right track: you'll need to await an Async function to put a delay in the middle of your method. The button click will notify the async function to finish.
    You could write a custom function which returns a Task and waits for the notification from the button:
    Task WaitForButtonClickAsync()
    // wait for button click
    and then await that in your main function:
    async void BigNastyFunction()
    await WaitForButtonClickAsync();
    The next question is how to let the button click notify WaitForButtonClickAsync to return.
    We could spin up a worker thread and have it block waiting on a notification, but there is no need to complicate things like that: WaitForButtonClickAsync can just return
    Task.Delay(timeout, cancellation token) and then when the button click handler fires it can cancel the delay.
    See
    Asynchronous Programming with Async and Await and
    Async Cancellation: Bridging between the .NET Framework and the Windows Runtime for more information on cancelling a task.

  • Wait for a mouse click

    Really need help with this one. I'm writing a program to simulate a Risk game and I need to write a method to make two countries neighbors, which would be done by adding each the neighbor country to each country's neighbor's array. To do this, I will need to click on the country, click on the map and then click on the other country. My method gets the country's name but how do I tell it to wait for a mouse click before trying to get the second country's name???? I've tried everything but to no avail. Any help would be appreciated.

    Some object has to be made a mouse listener for the components that are representing countries (I guess there are multiple of these) and the map.
    It should have a variable to represent first country clicked on - a variable that is initially null. It will need another variable to store the information it obtains from the click on the map (location, or whatever). It responds more or less as follows:
    Cick on country:
    Is firstCountry null?
        If so make firstCountry the country that was clicked on and finish
        If not, do we have mapInfo?
            If so use firstCountry, the country that was clicked on and mapInfo to update the neightbour list. Then make mapInfo and firstCountry null. Then finish.
            If not, just finish (because we are waiting for a click on the map).
    Click on map:
    Is firstCountry null?
        If so, just finish (because we are waiting to start the process with a click on a country).
        If not, extract the information from the map and place in mapInfo. Then finish.
    As you can see "waiting" in a GUI is quite a complex business - nothing really pauses, rather it continues as usual until an event of the right "type" occurs. The listener maintains enough "state" (information) to know what it is listening for and to remember necessary information that it has heard and will use later.
    This is somewhat general. It is difficult to be more specific unless you post some code. It should not be pages of GUI code - just enough to illustrate the task of three clicks and an action.

  • Check button-click during for-statement

    hi,
    I have wrote an import-function that reads out a text-file.
    I want that the user of my GUI is able to stop the import by pressing an abort-button.
    unfortunately, java seems not to check for button clicks during a block of code is processed.
    therefore I am looking for a work around.
    thanks
    gammloop

    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial

  • Pause for user click missing after Seamless Tabbing fix.

    I am upgrading a project from Captivate 5.0 to 5.5. Two of the lessons that worked fine in 5.0 have problems in 5.5. Both lessons use the Tab key to move from field to field in a data row and then the Enter key to calculate at the end of the row. This worked fine in 5.0. In 5.5, pressing Tab caused jump to browser address window. I searched blog and found following solution to add:    so.addParam(seamlessTabbing:, :false:);        to the htm file generated when publishing the file. This is not a desirable solution for long term course maintenance, but it did work. Unfortunately a new problem then appeared. The project moved ahead without waiting for user input in the simulation exercises.
    For slides with click boxes using Tab shortcut key and no other interactive objects, the movie just skipped ahead without waiting for user click. I would like the project to pause until the user presses the Tab key and then move to the next slide.  The properties for the click boxes are:
    Action:
    On success: Go to the next slide
    Attempts: Infinite
    Allow mouse click - yes
    Shortcut: Tab
    Options:
    Captions: Failure only
    Others: Pause for Success/Failure Captions and Pause project until user clicks
    Timing:
    Display for: Rest of slide
    Appear after 0 seconds   (I have played around with this setting, but it does not seem to make a difference.)
    For slides with Text Entry, the failure captions display before the user has a chance to input anything. Sometimes the captions flash several times at random. I would like the failure captions to only display when the user  enters an answer that does not match the stored answers.  The properties for the text entry boxes are:
    General:
    Default text: blank
    Retain Text - checked
    Validate User Input - checked
    Var Associated: Text Entry Box ## (## changes from slide to slide)
    On Focus Lost: No action
    Action:
    On Success: Go to the next slide
    Attempts: Infinite
    Shortcut: Tab
    Options:
    Captions: Failure only
    Others: Pause for Success/Failure Captions
    Timing:
    Display For: Rest of slide
    Appear after: 0.5 sec.
    Pause After: 1 sec
    Transition: No Transition
    To test whether it was something I was doing in the editing, I went back to the original 5.0 version of the lesson and imported into 5.5 again and published without doing any editing. The lessons that worked fine in 5.0 did not work in 5.5. Then I tried replacing all the click boxes with new ones created in 5.5. That did not work. I tried adjusting the timing. That did not work. For the text entry boxes, I tried using Show Button, creating transparent button with Tab shortcut. That did not work. Several of these suggestions were ones that I found elsewhere in the Blog with similar but not identical problems. I never found a problem that combined the seamlessTabbing with the missed pauses.
    I am puzzled and frustrated that these lessons that worked fine in 5.0 don't work in 5.5. Our primary edit is only to update the screen images and add a few new fields. I would often reposition an object on the slide, but not change its properties. Since most of the lessons are working fine in 5.5 and only these two that heavily use the Tab key are not working in 5.5. I don't really have the option of going back to 5.0. I need to put them in an aggregator and they all need to be the same version.
    Is there a patch or a quick fix? Also, can the patch to the htm file be built in or is that what is causing the problem? For future course maintenance, it will be complicated to have to treat these two lessons specially. Also, we usually link to the swf file and not the htm file. Our users often use browsers other than Internet Explorer.
    Any suggestions?   Thanks in advance.

    It would seem Intego Virus Barrier X6 has an intermittent habit of putting the IP address of Apple TV into the Blocked Addresses list despite having checked the 'Trust Apple TV' box and inputting the address into the Trusted Addresses list. Over the course of less than a year this has occurred approximately 4 times to me. My last variation on getting to the root of the problem was to lock the settings with the padlock. I will monitor the situation and should it happen one more time will notify Intego of this 'bug'.

  • Issues with "wait until mouse click"

    when I put wait until mouse click it doesn't register mouse down or mouse up. Because of that, my game is sloppy and skips some scenes if I accidentally hold down my mouse for more than a split-second click. Is there any way to manipulate the wait for mouse click behavior so it works only when the mouse button is released?

    Hmm, I wonder if he figured it out already, since he didn't even answer your question.  He seems to be talking about the built-in "Wait for Mouse Click or Key Press" behavior in the behavior library.  Sometimes those behaviors can become overly complicated for the simplest of things.  I recommend you just go ahead and roll your own frame script, as EtchK was implying.  It's pretty easy, you just need two short handlers:
    on exitFrame
      go to the frame
    end
    on mouseUp
    -- do whatever
    end

  • What should I do if the iphoto keeps on saying that "Plz wait for import to complete" when i click the close button but it is not importing photos? How can I close the iPhoto? I try to switch my mac off but it doesn't work. Thanks.

    What should I do if the iphoto keeps on saying that "Plz wait for import to complete" when i click the close button but it is not importing photos? How can I close the iPhoto? I try to switch my mac off but it doesn't work. Thanks.

    You should be able to select Force Quit from the menu beneath the Apple icon in Finder
    and choose to Quit iPhoto from there, without messing up the Mac OS X in the process.
    OS X - Support
    Not sure if rebuilding the iPhoto library would help this issue. However if you had to
    turn off the computer without the correct method (unplug, etc; instead of menu choice)
    the system may have accrued damages and should be checked, maybe repaired by
    use of the Disk Utility in the system. Or restart the computer in Safe Boot mode, then
    run 'repair disk permissions' while it is running in that reduced mode; then restart after.
    •Understanding Safe Mode - tuts+ computer skills tutorial:
    http://computers.tutsplus.com/tutorials/understanding-safe-mode--mac-59897
    •OS X: What is Safe Boot, Safe Mode?
    Suggestions on how to use Safe Mode in article, to resolve issues, may be helpful.
    There likely are other means to rectify troublesome applications, including reinstall.
    Be sure to backup your music, image, video, and other work on an external drive
    or suitable device as a precaution against loss should there be a hard drive failure.
    iPhoto - Mac Apps - Apple Support
    There should be some tips and help information using iPhoto via this tiny Support link.
    Good luck & happy computing!

  • Wait for a button click

    Hi,
    Here's the problem :
    my main class calls :
    LoginContext loginContext = new LoginContext("Main",
    new DialogCallbackHandler());
    I've made a DialogCallbackHandler class which opens a JFrame with 2 fields (TextField & PasswordField) and a button "ok".
    But the LoginContext wants immediately an answer (the login & the password). How can I make the loginContext waiting for the button click.
    I tried with a
    while(!buttonClicked);
    but it's not a good solution.
    I also tried with a Thread inside this loop while and sleeps (during a 500 ms). But I think there's a better solution...
    Can I make a wait, and a notify for this or not.
    Thank you for your help.
    Yann
    -- http://www.objectweb.org/jonas

    Why don't you use the JOptionPane class.
    I think it provides all that you need.
    For example use the method :
         String pass = "azedvge";
         JPasswordField passwordField = new JPasswordField(20);
         int result = JOptionPane.showConfirmDialog(parentComponent, password, "Password check", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
         if (result == JOptionPane.OK_OPTION) {
              String p = new String(passwordField.getPassword());
              if (p.equals(pass)) {
                   // OK !
              else {
                   System.exit(0);
         else {
              System.exit(0);
    I hope this helps,
    Denis

  • Waiting for a mouse click in a single thread

    Here's my problem:
    I'm working on a program I didn't initially create, and I picked it up from the rough midpoint of its evolution. It is a single thread AWT program, with a mouseListener interface already implemented.
    Here's my problem. In a game setting, we have two players. It is no problem when both are computer controlled. When player one is controlled by a human, I need to wait for a mouse event before returning, because upon returning player two moves (regardless of its player configuration).
    I can't do any kind of busy waiting because it is a single thread. I'm looking for some kind of option besides making the program multithreaded. This also makes it difficult to use some sort of boolean variable, though I don't think it's impossible.
    Thanks in advance for any help.
    Eric

    #9 - You are correct in your assumptions. I agree it's
    not the best model, but it worked for the original
    purpose, which was to have one player always
    controlled by the computer, and the option of
    selecting a second player as being either human or
    computer. Since each move is made manually - that is,
    for a move to be made, it requires user input - there
    was no harm in returning from a function, because it
    had no immediate computation. The requirements have
    just changed, and now I must allow both players to be
    selectable. This presents a problem in that I have to
    wait for the move actions to finish before
    proceeding.Understood.
    >
    My only question is, how can I access the AWT thread?You mentioned in an earlier post that you have action listeners. As triggered by user events, these are always called on the AWT thread. For example:
    import javax.swing.*;
    import javax.awt.event.*;
    JButton button = new JButton( new AbstractAction {
            public void actionPerformed(ActionEvent e) {
                synchronized (myMonitor) {
                    myMonitor.notifyAll();
        });This button can be added to some swing UI. If clicked on, then actionPerformed will be called on the AWT thread, and any threads waiting on myMonitor will be notified.
    I see what you are saying - it's almost exactly what
    my coworkers told me - but I don't have the knowledge
    to implement it, which is why I'm here. Creating a
    monitor object isn't a problem (makeMove() would need
    to be synchronized, otherwise you wouldn't be able to
    call wait()),I recommend using a separate object for the monitor, especially if you are already using synchronized, so that you know exactly how each object's lock is being used. If you're sure it is safe, then there is nothing wrong with using the object itself as the monitor, as you suggest, however.
    but I'm not sure what you mean by the
    action handling method should be called on the AWT
    thread.Just that any action listener method is always called on the AWT thread in response to user action.
    Dave

Maybe you are looking for