Start/Stop Buttons and infinite loop exit

I am trying to make a GUI with a Start/Stop and an Exit button. Initially the button will have the label "Start". When i push it, its label should become "Stop" and an infinite loop function will begin. I want the loop to run until i press the Stop or Exit button.
The problem is that when the loop starts i can't press neither of the buttons. The "Start" button changes its label into "Stop" only if i make the loop finite and it ends.
Here is the source:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class StartStopButtons extends JFrame{
    Component visualComponent = null;
    JPanel panel = null;
    JLabel statusBar = null;
     public StartStopButtons() {
          setSize(160, 70);
          getContentPane().setLayout(new BorderLayout());
        panel = new JPanel();
        panel.setLayout(new BorderLayout());
        getContentPane().add(panel, BorderLayout.CENTER);
        final JPanel panel_1 = new JPanel();
        panel.add(panel_1, BorderLayout.CENTER);
        final JButton startButton = new JButton();
        startButton.addActionListener(new ActionListener() {
             public void actionPerformed(final ActionEvent e) {
                String action = e.getActionCommand();
                if (action.equals("Start")) {
                     System.out.println("Start Loop");
                     startButton.setText("Stop");
                     myLoop ();
                if (action.equals("Stop")) {
                     System.out.println("Stop Loop");
                     System.exit(0);
        startButton.setText("Start");
        panel_1.add(startButton);
        final JButton exitButton = new JButton();
        exitButton.addActionListener(new ActionListener() {
             public void actionPerformed(final ActionEvent e) {
                String action = e.getActionCommand();
                if (action.equals("Exit")) {
                    System.exit(0);
        panel_1.add(exitButton);
        exitButton.setText("Exit");
     public void myLoop() {
          for (int i = 0; ; i++)
               System.out.println(i);
     public static void main(String[] args) {
          StartStopButtons ssB = new StartStopButtons();
          ssB.setVisible(true);
}

I works just fine. Here is the source and thanks for the help.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class StartStopButtons extends JFrame implements ActionListener, Runnable{
    Component visualComponent = null;
    JPanel panel = null;
    JLabel statusBar = null;
    Thread thread;
    JButton startButton;
     public StartStopButtons() {
        try {
            UIManager.setLookAndFeel(
                UIManager.getSystemLookAndFeelClassName());
        } catch(Exception e) {}
          setSize(160, 70);
          getContentPane().setLayout(new BorderLayout());
        panel = new JPanel();
        panel.setLayout(new BorderLayout());
        getContentPane().add(panel, BorderLayout.CENTER);
        final JPanel panel_1 = new JPanel();
        panel.add(panel_1, BorderLayout.CENTER);
        startButton = new JButton();
        startButton.addActionListener(this);
        startButton.setText("Start");
        panel_1.add(startButton);
        final JButton exitButton = new JButton();
        exitButton.addActionListener(new ActionListener() {
             public void actionPerformed(final ActionEvent e) {
                String action = e.getActionCommand();
                if (action.equals("Exit")) {
                    System.exit(0);
        panel_1.add(exitButton);
        exitButton.setText("Exit");
     public void actionPerformed(ActionEvent e) {
          String action = e.getActionCommand();
          if (action.equals("Start")) {
               startButton.setText("Stop");
               thread = new Thread( this );
               thread.start();
          if (action.equals("Stop")) {
            System.exit(0);
     public void run() {
          myLoop();
     public void myLoop() {
          for (int i = 0; ; i++)
               System.out.println(i);
     public static void main(String[] args) {
          StartStopButtons ssB = new StartStopButtons();
          ssB.setVisible(true);
}

Similar Messages

  • Single start/stop button for looping movie

    Dear Friends,
    I apologize if this has been addressed already in the forum, as I have had no luck searching here or the web in general for a solution.
    I currently have a 23-frame multilayered single-scene animation designed to loop continuously which I would like to add to my portfolio. As such, I am adding a Play button, which I would like to toggle to a Stop (or Pause) button. I currently have an instance of the Play button ("playButton") created.
    (You can find this at pineboxmovingco.com/gear_redux.swf)
    Besides imploring your assistance in providing the code, I must also ask if this requires (and best practice for) inserting an additional frame at the beginning for the ActionScript, as well as where/what layer to add an instance of the Stop button. I would like the movie to be stopped by default, presenting the Play button, toggling to the Stop button, and back to the Play button, each upon release.
    Thank you so much in advance!
    Michael T
    Phila, PA

    So, Ned, insert the stop(); command - with no other code - on each keyframe of the MC like so:
    Then, return to Scene 1 and select the MC, inserting the code:
    With an additional "stop" command in the first frame:
    I must be missing something as it is continues to loop. Any further assistance would be greatly appreciated...
    Michael
    (UPDATE: Replaced second image with AS reflecting replacement of XXX with "1".)
    Message was edited by: turnerator

  • I can browse the web but when I go to play video or you tube it will start stop over and over almost like it is buffering could this be the router all other non iPad devices work

    I can browse the web but when I go to play video or you tube it will start stop over and over almost like it is buffering could this be the router all other non iPad devices work

    How are you trying to play them, in the iTunes store or the Music and Videos apps ? Downloaded and synced music and videos should be in the Music and Videos apps, and you can stop content that is only in the cloud from showing in them via Settings > iTunes & App Store > Music and Videos 'off' (under the 'show all' heading).
    If you don't have your music and films/TV shows in those two apps then you should be able to download them into those apps via the Purchased tab in the iTunes store app.

  • How do I create a start/stop button for each separate while loop within my program, when each of them does a different task?

    I have a multimeter VI with separate while loops to accomplish the different tasks of reading  voltage, current, etc. Each while loop has a stop button, but I need a button that will have to be pressed in order for the while loop to even start. I tried putting another while loop around the present one, but it still has to run once before it will stop. I want the user to have to press the button before it runs, because they interfere with each other.
    I am just learning so patience and your kind assistance is greatly appreciated!
    ElectroKate

    iZACHdx wrote:
    Hello,
    I'm not entirely clear with everything you have going on and what you want your final functionality to be, but you can use sequence structures to prevent a loop from starting until the user presses a button like this:
    -Zach
    I have to ask, why is an NI employee using examples using sequence frames? The same thing could be accomplished using data flow by simply wiring the value of the first stop button out of teh first while loop and connecting it to the second loop. This would then use data flow to control the sequence. Why show new users bad programming methods?
    As to the original question I would concur with altenbach on using an event structure.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • How to start/stop 2 parallel while loops

    My question might be simple to answer for experts, but as a Labview beginner would be great to receive your help:
    I hav a VI with two parallel while loops. The first loop runs in a tact of 100 ms to aquire voltage, speed and to output a speed setpoint for a motor in the same tact, read from a table.
    Finally all values are written to a log-file.
    The question: As soon as I run my VI, data logging starts too and my motor runs. How can I implement a button to start all loops parallel, and how can they be parallel be stopped too if I want to stop measurement? Tryed to set a local variable for both stop buttons but it didn´t work.
    Thanx to all, Markus
    Attachments:
    screenshot.JPG ‏74 KB
    Measure and log data.vi ‏147 KB

    SnowMule wrote:
    Starting the two is easy; use the error cluster to enforce dataflow.
    Stopping them is a little trickier; the code you have now isn't very expandable so I'd recommend finding a different architecture.  A notifier functions like a queue with a size of 1, a queue works well for sending commands/data between loops.
    There is one other significant difference between queues and notifiers. A queue can only have one reader. If you have multiple readers of a queue who reads it will be random. A notifier can have multiple listeners. It fact, that is it's purpose.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

  • How to add stop button to myDAQ loop

    Hi ,
    im last semester student and during my final project im recroding lung sound with electret microphone sampling it with myDAQ and writing it to a wav file. the acquisition mode is "continuous samples" , the recording time is changing from time , i want to add a "STOP" button , which will be pushed when i finished my recording . If i push on the "abort execution" button , the wav file is empty , and so on the graph. any suggestions ?
    thank you in advance.
    Attachments:
    Record.vi ‏78 KB

    Like this
    By the way, that Abort VI button is not for stopping your loops.  I just kills execution wherever it may be.  It should only be used as a last resort if your stopping code is not working properly.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Record_BD.png ‏88 KB

  • Stop Button and Autoplay

    Because the old threads don't get any more kudos I feel I must start a new one, and yes you can point to the old one but this will hopefully raise the subject to more discussion. Why on earth doesn't Spotify have a "STOP" button? If I want to stop the music I'm playing, I STOP it, not PAUSE it. It's really annoying to have to start at the middle of a song when you wanted to start over. Why can't such a simple feature be enabled? I don't care if it's not on the interface, but please add the functionality so we can keybind it elsewhere. 
    Second issue is the autoplay when switching songs. Just add an option of having the music be on hold when changing tracks. Some of us wants to see wich song is about to be played before we start it. Something about discretion, and not wanting to hear every first second of every song you skip. 
    Please make this happen and you'll make many souls very happy.
    Sincerely
    Magnus

    Why there isn't a simple stop button to stop playback included in the Windows client by default escapes me.The only way to stop playback as it stands now is to close the client or pause.
    I want to stop, not pause. Like when you press the stop button on many other media players. Something like this is what is needed...

  • HashMap, HashSet and infinite loop

    hi,
    our code ended up in an infinite loop while parsing the entries of a HashMap with this code:
            Iterator it = myHashMap.entrySet().iterator();
            while (it.hasNext()) {
                field = (Map.Entry) it.next();
                // code that access content of "field"
            } as the loop creates some kind of objects, the JVM terminated with a out-of-memory. luckily we got a heap-dump file and that shows:
    - the hash-map has 325 entries
    - the loop was iterated more than 3 million times
    - the iterator "it" has a current and a next field pointing at the same element of the HashMap
    a snapshot of the heap-analysis of the iterator can be seen at
    http://www.sbox.tugraz.at/home/a/archmage/hashset/EntryIterator.html
    maybe the HashMap was accessed concurrently, but then there should be a ConcurrentModificationException.
    we are using
    > java -version
    java version "1.4.2_12"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_12-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_12-b03, mixed mode)for me, this looks like a JVM bug, but i cannot really believe that (and i could not find a bug stating this behaviour).
    is there anything i did not notice during using hashmaps/hashsets/iterators?
    regards, werner

    there should be aConcurrentModificationException.
    Not necessarily. The iterators cannot always detectConcurrentModificationException.
    api-docs of HashMap say:
    A structural modification is any operation that adds
    or deletes one or more mappings
    if the map is structurally modified at any time after
    the iterator is created, in any way except through
    the iterator's own remove or add methods, the
    iterator will throw a
    ConcurrentModificationException.
    for me, that means, the iterator should detect any
    "add" or "delete" operation like map.put(...). am i
    wrong? or are the docs wrong here?Immediately AFTER the paragraph you quoted, it says
    Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html
    Furthermore, did you READ what I said after that?
    It's FAR MORE LIKELY to be a result of data corruption, rather than multiple simultaneous iterators.

  • Worth it? Auto start/stop services and change iptables rules

    I have recently set up a crontab to start/stop services based on my schedule, such as when I'll be home or away. I intend to only have a service running when I'll probably use it.
    I also integrated rules for iptables into the start/stop of the services (systemd), so they automatically modify rules to accept/reject on their ports when the services start/stop.
    I am behind a router, so I only forward outside ports I use like ssh (which is not on port 22). I manually forward ports, but am looking at UPnP. This is my home network so I should be able to trust the devices on it.
    Now, to my question. Is it worth the time and effort to set this up? Would it be fine to just enable the services I use, let them run and always have firewall ports open for them? I feel like it's good to limit the time that ssh is running, but what about services not open to the Internet? Resources aren't really an issue. What do you guys think?
    I enjoyed learning about systemd, iptables, and cron in the process of setting it up. I'd just like to also learn about how much benefit there actually is, or if anyone has other ideas. Or if it's something that could go on the wiki (not really cron, but maybe the iptables/systemd stuff).

    I'd say, if resources aren't an issue; why limit the time ssh is reachable from the outside? You should have PasswordAuthentication and RootLogin disabled anyway so your vulnerability doesn't really decrease by updating iptables? This script probably works fine until you forget about it and it makes a boo-boo; making your machine unreachable.

  • Service start stop scripts and Nagios scripts

    Hello. Are there some "official" service start stop scripts somewhere? And: Has somebody already written a Nagios monitoring script for Oracle NoSQL? Thanks, Jesus.

    Hi. Yes, but I mean something like service kvclient start / stop / restart / status, and using e.g. daemon without nohup. Of course one can be written, e.g. I have a simple one based on a script I found in internet long time ago for Cassandra, but then by Murphy's Law you will probably have an "official" one in the .124 version : - ).

  • Starting/Stopping iAS and OC4J containers

    I created the following two batch files to start and stop my iAS Infrastructure. I found that if I used the services settings of automatic all did not go well.
    start.bat:
    @ECHO OFF
    cls
    ECHO About to start the listener
    net start Oracle9ias_InfraTNSListener
    ECHO About to start the database
    net start OracleServiceIASDB
    ECHO About to start the OID monitor
    e:\ora9iasinfra\bin\oidmon start
    ECHO About to start the OID server
    e:\ora9iasinfra\bin\oidctl server=oidldapd configset=0 instance=1 start
    ECHO About to start the website
    net start Oracle9ias_infraEMWebsite
    ECHO About to start opmn and OC4j
    e:\ora9iasinfra\dcm\bin\dcmctl start -ct ohs
    e:\ora9iasinfra\dcm\bin\dcmctl start -co OC4J_DAS
    stop.bat:
    @echo off
    ECHO About to stop the website
    net stop Oracle9ias_infraEMWebsite
    ECHO About to stop opmn and OC4j
    e:\ora9iasinfra\dcm\bin\dcmctl shutdown
    ECHO About to stop the OID server
    e:\ora9iasinfra\bin\oidctl server=oidldapd configset=0 instance=1 stop
    ECHO About to stop the OID monitor
    e:\ora9iasinfra\bin\oidmon stop
    ECHO About to stop the database
    net stop OracleServiceIASDB
    ECHO About to stop the listener
    net stop Oracle9ias_InfraTNSListener
    When I execute the batch files sometimes they work and sometimes they don't, for example after starting occasionally the Apache process has not been created, and sometimes processes won't stop.
    However if I enter each command seperatly all works OK. Can anyone suggest a reason for this. Also after starting the website manager the process manager for both the infra and ias are started (I have both installed on the same machine - this works fine apart from this batch file problem.
    Terry Bennett

    Terry -- You will probably have better luck on the General Oracle9iAS forum at:
    http://forums.oracle.com/forums/forum.jsp?id=466592
    Thanks -- Jeff

  • AS 3.0 Output Error for Start / Stop Buttons

    In trying to understand ActionScript 3.0 mouse events, I have
    followed the online video under Flash / ActionScript / Getting
    Started wit ActionScript 3.0 presented by Justin Everett-Church. At
    least I don't see any syntax errors.
    I am not getting a Compiler error, but I get this warning in
    the Output tab: WARNING: Actions on button or MovieClip instances
    are not supported in ActionScript 3.0. All scripts on object
    instances will be ignored.
    I understand what it is telling me. Actions on button
    instances are not support in AS 3.0. But then why does the video
    tell me to name a button instance and then go on to refer to it in
    the ActionScript?
    The movie still works fine. I just get this Output warning.
    Should I be concerned? I am using Flash CS3 Professional Version
    9.0
    Another peculiar thing is this. The code shown below DOES NOT
    generate an Output error on one on my FLA files, but it DOES on
    three others that have exactly the same button names and AS 3.0
    code (shown below). I don't see any differences. I even copied and
    pasted the code from the one that didn't produce the warning to the
    others that did. Again, the movies seem to work fine, but I get the
    Output warning.
    Here is my ActionScript 3.0 code (I named the three button
    instances: stopBtn, playBtn, restartBtn)
    import flash.events.MouseEvent;
    stopBtn.addEventListener(MouseEvent.CLICK, stopDemo);
    function stopDemo(event:MouseEvent):void {
    this.stop();
    playBtn.addEventListener(MouseEvent.CLICK, playDemo);
    function playDemo(event:MouseEvent):void {
    this.play();
    restartBtn.addEventListener(MouseEvent.CLICK,restartDemo);
    function restartDemo(event:MouseEvent):void {
    this.stop();
    this.gotoAndPlay(1);

    Are you extending the layer that has the function for the length of the timeline like I showed in the example file I made for you?  I put the code for the other frames on a separate layer to make sure that the one being shared is not cut short.
    I think I also already mentioned that you should go into the Flash Publish Settings and select the option to Permit Debugging so that the error message indicates which line of code is causing the problem.

  • Windows 8.1 start menu button and charms frozen

    So sometimes when I try to click the bottom-left start icon, it suddenly does not work. I hover over it but it doesn't change color nor
    work at all, but after i restart explorer.exe from task manager it starts working again. This happens randomly, and can happen again in a short while after restarting explorer.exe. I have this same problem on another computer running Windows 8.1 and I have
    not installed anything extra on that computer yet. I saw someone say disabling OneDrive syncing would solve this problem, but even if I did that it is still occasionally freezing up. This has been pestering me a while now and is a bit problematic since even
    event viewer doesn't have any information on it.
    The problem doesn't seem to be explorer.exe as a whole, since the taskbar works and windows open and close properly. I can also view and use
    explorer.exe normally (browse files and folders and open programs). However, the charms do not appear and the start button in the bottom-left doesn't work at all, i can't click it to get to the start screen nor right click it to show the menu. In other words
    it seems to be the start menu freezing, but there's nothing in event viewer that would indicate a problem. Restarting explorer.exe fixes this problem temporarily, but it keeps happening every now and then.

    To anyone experiencing this, it is a bug in Win 8.1 which I can replicate at will.
    Reinstalling your system as suggested by MS engineers will not fix this.
    To force the bug to appear:
    1. Grab a desktop Icon (recycle bin, any shortcut) and move this up to the top left hand corner without letting go of the mouse button. Drop shortcut anywhere on desktop. Without an Icon the mouse pointer would initiate the recent apps.
    2. To check that the first step has worked, try and invoke charms by moving mouse to top right hand corner.  If Charms do not appear then the bug has been triggered.
    3. Now move mouse over start button (no click), move away then back again. Now the start button is locked.  If you unlock the taskbar you can move it to any other position (top, left or right) and the start button works.  Move taskbar back to the
    bottom and the start button still does not work.  Only way to get it working again is to restart window explorer in task manager.
    To avoid this happening all you need to do is disable recent apps corner.
    1. Right click desktop.
    2. Click Taskbar and Navigation
    3. Click Navigation tab in the properties window
    4. Uncheck "When I click the upper-left corner, switch between my recent tabs."
    Now the bug cannot be triggered as above to make the start button stop working. You have to remove this feature which is pretty hopeless on a desktop anyway.  Its better than restarting Window explorer every time.
    I can replicate this on any desktop or laptop, fresh install or old. Not sure about any touch screen machines. I can also trigger this in VMPlayer\Virtual Box and the Modern IE VM images that MS provide.
    Now the MS engineers can replicate this on their machines, and maybe if we are lucky they will FIX it!!!!
    MS please acknowledge that this is a bug.
    Maybe the issue is due to the windows button not being redrawn on the screen once triggered as it still works when taskbar is moved (graphic card drivers). Could not find anything use full in the system logs.
    Just noticed also that the charms also breaks if you drag an Icon up to the right hand corner. Once triggered Charms stops working, start button is not affected with the above work around configured.
    MS please read this and reply.

  • Can't add pin it button or amazon button and can't exit customization

    I cannot add the pin it button or the amazon button through customization. I also have a problem with the whole customization process. I cannot exit. I have a little screen thing on customization that when I tried to open was in Japanese and really afraid of what it could have done to my computer. Here is the screen shot of it on customization.

    You can try to click the Restore Defaults button in the Customize palette.
    You can check for problems with preferences.
    Delete a possible user.js file and numbered prefs-##.js files and rename (or delete) the prefs.js file to reset all prefs to the default value including prefs set via user.js and prefs that are no longer supported in the current Firefox release.
    *http://kb.mozillazine.org/Preferences_not_saved
    *http://kb.mozillazine.org/Resetting_preferences

  • Using the back button causes infinite loop between articles

    Hi i have a folio that has a series of projects, and i wanted to use the back option as various access points to each project
    goto://FolioNavigation/lastview
    but each project has an image article associated with it, and this has a button on it back specifically to the project main article. But when u click the back button now on that main artcile, it takes  u to the image article, not back to where the person wud have wanted to be.
    I cannot think of a work around other than going back to using specific page navto but that means determining the access point which is not possible. Or duplicated the articles entirely.
    Any help appreciated.
    Rob

    found solution. you have to use the goto://FolioNavigation/lastview
    in the back option on the image page as wel. then it knows not to cause infinite loop

Maybe you are looking for

  • Connecting a 2nd Palette monitor to iMac

    I have an iMac 24" 28Ghz (1Mac,8.1) and want to connect a second palette monitor to the mini DVI port, using a mini DVI to VGA connector. A search of the forum shows issues with cursor jumping and wrong resolutions. I really want to run my Adobe CS4

  • Central 5.4 stops printing, a reboot of the server is the only way to fix the problem

    Hi, We are running central 5.4 on windows 2000 SP4, this has worked for ages but has just started with an intermittent fault.  When we send some output it suddenly stops printing, and no forms sent to central will be printed, the only way to get them

  • Dreamweaver CS6 / CC crashes after Mac OSX 10.9.3 update.

    Updated today to Dreamweaver CC, and the issue persists. My 'local' files are stored on a Windows Vista server on the LAN. Everything worked OK until 2 days ago, so I'm almost sure the issue is related to the OS update. I can open a file, work on it

  • Reading a file whoes name is dynamically modified by a predecessor program

    Hi All, I have a requirement where I need to read a file from application server but the catch is the file name is stamped with date and time by a predecessor program. Thanks, Gaurav.

  • Problems to print my book

    I have made a book of 26 pages with photos and text, but I cannot order the book, since the menu " buy the book" remains in grey. 2 pages have a warning sign, but I don't understand why. One is with one photo and a column of text. The sign is on the