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.

Similar Messages

  • 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.

  • 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

  • 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.

  • Always need Disconnect power, press the power button wait for 10 seconds...

    I bought a HP computer for a couple of years ( Pavilion a6695it  ) It always works well. But in recent days, I can not start up it. I tried pressed power button on the front of the computer, nothing happend. Then I searched in hp site. finnally, I find this article http://h10025.www1.hp.com/ewfrf/wc/document?docname=c00241069&tmp_task=solveCategory&cc=it&dlc=it&lc...
    In english version the article is here: 
    http://h10025.www1.hp.com/ewfrf/wc/document?docname=bph06788&cc=us&destPage=document&lc=en&product=3...
    Power supply light is on or flashes
    Perform the following steps, in order, until power is restored or it is determined that there is a hardware failure:
    CAUTION:This product contains components that are easily damaged by ElectroStatic Discharge (ESD). To reduce the chance of ESD damage, work over a non-carpeted floor, use a static dissipative work surface (like a conductive foam pad), and wear an ESD wrist strap that is connected to a grounded surface, like the metal frame of a PC.
    Disconnect everything from the computer, including the power cord.
    With the power cord disconnected , press the power button on the front of the computer and wait for ten seconds.
    This is work for me. But now, my computer always need this methond that it can be started up.
    Disconnect power -> press the power button and wait for ten seconds -> then the system will  start up
    So my question: where is the problem? Which part is broken and i should replace? Thanks.
    regards,
    Youli
    This question was solved.
    View Solution.

    Hello youlichika,
    Welcome to the HP Forums, I hope you enjoy your experience! To help you get the most out of the HP Forums I would like to direct your attention to the HP Forums Guide First Time Here? Learn How to Post and More.
    I understand that you are not able to power on your desktop, and I would be happy to assist you in this endeavor! 
    In following the document for Troubleshooting Power Supply Issues, were you able to follow steps 3-9? If so, what were the results?
    If you have come to the end of the document, and you still have to drain the power from the computer to power it on, you can find a replacement part (5188-2627) through one of the sites available by following this link.
    I hope this helps!
    Best Regards   
    MechPilot
    I work on behalf of HP
    Please click “Accept as Solution ” if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos, Thumbs Up" on the right to say “Thanks” for helping!

  • Wait For A Button Press

    Hey, I am currently creating a game and need to know how to wait for a certain button to be pressed. A popup message comes up that tells the user to press a button, then I need to wait for the button to be pressed. Then once the button is pressed, I want another message to come up. The problem is, I have no idea how to wait for a button press after the first message comes up. Instead it just displays the first message, then the second directly after.
    Thanks

    So you have a button that is always present. Normally clicking the button does nothing. But sometimes a message shows up, in which case if the user clicks the button, something happens. Right?
    UI principles aside (it's bad form to display a button that does nothing), this is pretty simple.
    Create a field to track whether the button does anything. For example:
    private boolean buttonActive = false;In your action listener for that button, first check the value:
    public void actionPerformed(ActionEvent e) {
        if (buttonActive) {
            // do your thing
    }If the buttonActive is true, it does something, otherwise it does nothing.
    After you display the message, set buttonActive to true. When you want the button to become a brick again, set it to false.

  • Wait for user to select the OK button

    For my application I cannot use a simple MessagePopup where the user must select the OK button to continue.
    I created a new panel with just a text message and an OK button to act like a MessagePopup.
    When I call InstallPopup and the Panel box pops up I want to wait until the user selects OK before continuing just like the MessagePopup.
    How can I accomplish this?
    Thanks!
    John W.
    Solved!
    Go to Solution.

    You can use GetUserEvent () function. In the scenario you have depicted you must have all controls in the popup panel set as "Normal" and only the OK button set as "Hot" (The default control mode). The callback the must handle the panel can be structured like this:
    int pnl, ctl, handle;
    // some code here
    // Code to handle the popup
    handle = LoadPanel (.....)
    InstallPopup (handle);
    GetUserEvent (1, &pnl, &ctl); // Wait for the user to press OK button
    DiscardPanel (handle);
    // The rest of the code here
    This help topic gives you additional informations on this subject.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?

  • 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!

  • Delete Record Behavior doesn't wait for Submit button

    I have master / detail page set.  From the detail set there are links to delete or update a record.  When I click the link to delete the record, it goes to the   confirmation page with the correct record.  Now, when I add the delete record server behavior and a submit button, this is what happens.  As soon as I click the link to go to the delete confirm page, the record deletes and the page redirects to the page I put in the server behavior.  It doesn't show the confirm page and doesn't wait for me to hit the confirm button.  The page runs and successfully deletes the page from the DB.
    How do I get it to wait until I hit the submit button?

    You need to surround your delete query with an "If" statement that checks for a confirmation variable of some sort, then when the user clicks the confirmation link you can pass the necessary variable and the ID of the record the delete query is expecting.
    As an alternative you could use a JS alert fuction to ask the user if they are sure they want to delete the record and then allwo the delet to run after confirmation. To do this you could use code like this...
    <input type="submit" name="DELETE" value="DELETE"
       onclick="return confirm('Are you SURE you want to DELETE this record?')">
    Lawrence   *Adobe Community Expert*
    www.Cartweaver.com
    Complete Shopping Cart Application for
    Dreamweaver, available in ASP, PHP and CF
    www.twitter.com/LawrenceCramer

  • Macbook air 2013 needs power button pressed for 10 seconds before it turns on?

    macbook air 2013 needs power button pressed for 10 seconds before it turns on? also I've tried resting PRAM but when i press the 4 buttons before the start up screen it never restarts again? please help!

    Reset SMC.     http://support.apple.com/kb/HT3964
    Choose the method for:
    "Resetting SMC on portables with a battery you should not remove on your own".
    If this does not help, contact Apple.
    Genius Bar reservation:
    http://www.apple.com/retail/geniusbar/
    Best.

  • 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

  • HT201263 I holding home button iphone 5 does not start it is blank.  itunes shows waiting for iphone and the applle icon and under line appears

    I unable to restore my iphone 5.  I keep on holding power and home button but it does not show apple icon and cable picture.  If  I try to restore from itunes
    I get "Waiting for iphone" it stays forever and iphone show apple icon and line under it.

    Hi there jey_osman,
    You may find the troubleshooting steps in the articles below helpful.
    iOS: Apple logo with progress bar after updating or restoring from backup
    http://support.apple.com/kb/TS3681
    iOS: Unable to update or restore
    http://support.apple.com/kb/HT1808
    -Griff W. 

  • HT201263 Ipad 2 initially would turn itself completely off and have to be restarted with both buttons.  Got to point that sometimes didn't work without repeated efforts.  Restore stops when in the "waiting for ipad" part.  Tried recommended Apple restore

    Unable to turn on or do a restore.
    After installing IOS7 it would turn itself completely off sometime and have to be restarted with both buttons.  If I turned it off normally it would restart okay within an hour or so but overnight it would always go to hard off.
    Using both buttons would usually start it with the Apple logo on the screen until it came up.  Worked normally then.  Knowing something was afoot I did a restore.
    Now it will not turn on at all and I tried to restore in itunes but it stops at the point of "waiting for info from the Ipad"
    I tried the Apple forum "recovery-restore" process several times with holding down the home button and plugging in the USB but it did not respond. 
    When connected through itunes it is still recognized as needed to be restored but the process will not complete.
    Standing by.
    Bob

    Bob ...
    Might be something you have not tried here > iOS: Not responding or does not turn on

  • When I started my Mac the screen was white with the Apple logo and power motion icon running.  I attempted to turn off Mac then a message stating "Debugger called:  Button SCI . Also "Waiting for remote debugger connection."  What is my next step?

    When I started my Mac the screen was white with the Apple logo and power motion icon running.  I attempted to turn off Mac then a message stating "Debugger called:  <Button SCI>. Also "Waiting for remote debugger connection."  What is my next step?

    Hi , and a warm welcome to the forums!
    Could be many things, we should start with this...
    "Try Disk Utility
    1. Insert the Mac OS X Install disc, then restart the computer while holding the C key.
    2. When your computer finishes starting up from the disc, choose Disk Utility from the Installer menu at top of the screen. (In Mac OS X 10.4 or later, you must select your language first.)
    *Important: Do not click Continue in the first screen of the Installer. If you do, you must restart from the disc again to access Disk Utility.*
    3. Click the First Aid tab.
    4. Select your Mac OS X volume.
    5. Click Repair Disk, (not Repair Permissions). Disk Utility checks and repairs the disk."
    http://docs.info.apple.com/article.html?artnum=106214
    Then try a Safe Boot, (holding Shift key down at bootup), run Disk Utility in Applications>Utilities, then highlight your drive, click on Repair Permissions, reboot when it completes.
    (Safe boot may stay on the gray radian for a long time, let it go, it's trying to repair the Hard Drive.)
    If perchance you can't find your install Disc, at least try it from the Safe Boot part onward.
    If 10.7.0 or later...
    Bootup holding CMD+r, or the Option/alt key to boot from the Restore partition & use Disk Utility from there to Repair the Disk, then Repair Permissions.
    And sorry to report that OSX is more Widows like than ever, but….
    If that doesn't help Reinstall the OS.

Maybe you are looking for

  • Commerce Server and Visual Age 3.5

    I tried and was unsuccessful getting the Commerce server (3.11) to run under Visual Age 3.5. I can get it to start up correctly, but if I test a commerce application, Visual Age disappears with no messages. From my experiments, I think it is a proble

  • Constructing CSS photo gallery layout

    Hi, I'm on DW CS4 with an intel Mac. I am one (1) table away from having my site be purely CSS without tables. I have painstakingly placed each thumbnail manually and resized all the heights etc.  My Gallery actually looks good in IE 6, much to my su

  • NEWBIE question about java

    Why is the java compiler making two .class files for my swing applet? input > applet1.java output> applet1.class , applet1$1.class This is annoyin because it appears the applet1.class needs applet1$1.class to run. Unfortunately, my webserver (FreeBSD

  • Picking up only committed rows

    Hi, we run std 2012.  I want to write a proc that when it starts running only picks up rows from a table that were committed any time prior to start of execution.  Generally, the procs that insert to this table will wrap 1-n inserts inside a transact

  • HT1918 Chinese characters on Appel store

    I am living in Macau for 6 years. Close to Hong Kong. I recovered my IPad and my Wife iPhone. When I set my location for apple store. All the words became Chinese. I don't know Chinese. How do I set it back in English??? Regards