Infinite Loop Gui Problem

Hi all,
Well basically I have 3 classes; one is called the loader which has the main function and all it does is call the second class which is the GUI class. This class buils up the GUI. The Third class however is a class which has an infinite loop inside until a button on the GUI is clicked. HOWEVER... due to the infinite loop, the GUI stays inactive until the loop ends which basically is like having a crashed GUI and thus the button can never be clicked!!
What do you suggest? Shall the loader load the third class and the third class loads up the GUI? Or is that not practical?
Thanks all

Hi again,
I still have a similar problem.
basically whats happening is...
From the GUI I launch a class with an infinite loop !!
Part of the Loop is to await a connection and when connected, a new Class is again launched, it processes and closes itself, and returns back to the infinite loop !!
I would like to know how I can Detach from the infinite loop to keep the GUI working...
thanks all

Similar Messages

  • "Infinite Loop" Download Problem

    So I was downloading an album from iTunes, and one of the songs wouldn't download. When it reached the end of the bar, it would just reset, in an infinite loop. And the song is Album Only, so I can't just cancel the download and buy the song again. How do I fix this?

    Hi again,
    I still have a similar problem.
    basically whats happening is...
    From the GUI I launch a class with an infinite loop !!
    Part of the Loop is to await a connection and when connected, a new Class is again launched, it processes and closes itself, and returns back to the infinite loop !!
    I would like to know how I can Detach from the infinite loop to keep the GUI working...
    thanks all

  • ActionEvent/Setting gui text in an infinite loop

    Hi,
    I have set up a gui that contains ~ 100 JTextFields and one JTextButton
    Pressing the JTextButton on the gui triggers an action event that
    1.     establishes a socket connection w/ a server
    2.     reads input from the server in an infinite loop
    3.     should use the server data to dynamically setText in the various JTextFields found on the gui.
    for example, during one iteration of the infinite loop, the data may set the text of JTextField #1 to ?foo? and in a later iteration of the loop, the new data from the input stream may set the text of the same field to something else (e.g. ?bar?). Thus, the gui should show a dynamically changing collection of TextFields after the user presses the JTextButton.
    Problem: because of the infinite loop, NONE of the fields is ever updated (see pseudocode below). If I remove the infinite loop and simply have 1 iteration of the block of code within the actionPerformed method, the gui updates properly.
    How might I alter the code to a) maintain the server connection, b) continuously read from the input stream and c) have a dynamic update of the textfields w/in the gui?
    I've tried adding "this.paint(this.getGraphics());" within the infinite loop and it sort of works, but the updates to the gui are FAR SLOWER than the data that are streaming in from the server.
    Thanks for any help!
    The code looks something like this
    Public class abc extends JFrame
    Public abc()
         {initialize components}
    instantiate all textfields & button
    create various arrays
    public void initialize components
         (set up gui using gridbaglayout
         add actionListener to button)
    private actionperformed
    (establish socket connection w/ server
         read data from server in an infinite loop
         parse data and use information to setText on the gui)
    public static void main(blah blah)
         show abc();

    have the reading loop in a different class which will have its own Thread running aside from the main program's thread. This way your application will do both at once :)

  • Infinite loop problem

    Hi there,
    This is the second time I have posted this problem, as the last solution I was offered did not seem to work. Here is the problem:
    I have written a method to search through a text file for a word and replace it with another word. That word can either be on its own in the document or as part of another word. So, if the search word was "foot" and the replace word was "dog", the word "football" in the document would become "dogball".
    This method works fine, except for when the replace word is the same as the search word. Basically, if someone searched for "dog" and wanted to replace it with "dog dog" or even just "dog", the program goes into an infinite loop. I understand why it is doing this, but I don't know how to prevent it from happening.
    Now, to make it worse I have to stick to this array style structure and method of solving the problem. I know there is a way to do this by building temporary strings and then concatenating them at the end and returning them to their previous position in the array. The reason I know this is because a friend of mine has managed it. She also happens to be a girl.
    So, I am asking you all to assist in defending men's intelligence by helping me see where I am going wrong in this method. Please.
    Here is the method:
    // Search the document for a string and replace it with another string        
         public String [] SearchReplace() {
              // Declare variables to be used in the method
              String SecondSubstring;
              String FirstSubstring;
              int ReplaceNumber = 0;
              // Loop through the lines of text stored as strings contained in the array
              for (int i = 0; i < NumberOfLines; i++) {
                        // As long as the string contains an instance of the search string, run the method                    
                        while (StrArray.indexOf(SearchW) >= 0) {
                             // Make a string of all the characters after the search word
                             SecondSubstring = StrArray[i].substring(StrArray[i].indexOf(SearchW) + SearchW.length());
                             // Make a string of all the characters before the search word
                             FirstSubstring = StrArray[i].substring(0, StrArray[i].indexOf(SearchW));
                             // Concatenate FirstSubstring with the replace word to make a new string
                             String FirstHalf = FirstSubstring.concat(ReplaceW);
                             // Concatenate the new string with SecondSubstring to make the whole replaced string
                             String FullString = FirstHalf.concat(SecondSubstring);
                             // Put this altered string back to its original place in the array
                             StrArray[i] = FullString;
                             // Increment ReplaceNumber to count the replacements made
                             ReplaceNumber++;
              // Print the numbers of replacements made
              System.out.println("\nA total of " + ReplaceNumber + " changes made.\n");
              // Display the searched and replaced contents of the file
              return StrArray;
    Any suggestions, pointers or solutions would be much appreciated.
    Thanks very much.

    Doing it the "old fashioned" way:
    You need to keep track of a "from index" so you don't search through parts of the string you've already replaced:
           public static void main(String args[]) {          
              try {     
                   String[] lines = new String[] {
                        "the dog went up the dog hill",
                        "all dogs go to dog heaven",
                        "the dogball takes place on 3rd april"
                   lines = replace(lines, "dog", "dog dog");
                   for (int i = 0; i < lines.length; i++) {
                        System.out.println(lines);
              } catch (Exception e) {
                   e.printStackTrace();
         private static String[] replace(String[] lines, String searchWord, String replaceWord) {
              if (searchWord.equals(replaceWord)) return lines; // nothing to do          
              for (int i = 0; i < lines.length; i++) {
                   int fromIndex = 0; // from index to do indexOf
                   String line = lines[i];
                   while (line.indexOf(searchWord, fromIndex) != -1) {
                        final int index = line.indexOf(searchWord, fromIndex);
                        line = line.substring(0, index) + replaceWord + line.substring(index + searchWord.length());
                        fromIndex = (line.substring(0, index) + replaceWord).length();
                   lines[i] = line; // replace
              return lines;

  • [svn:fx-trunk] 10214: This fixes the problem that if two text components share the same textFlow there is an infinite loop involving updateDisplayList - damageHandler - invalidateDisplaylist - back to updateDisplayList.

    Revision: 10214
    Author:   [email protected]
    Date:     2009-09-13 07:33:58 -0700 (Sun, 13 Sep 2009)
    Log Message:
    This fixes the problem that if two text components share the same textFlow there is an infinite loop involving updateDisplayList -> damageHandler -> invalidateDisplaylist -> back to updateDisplayList.  The bug file was for TextArea which is RET but the same bug was in RichText as well.
    This example with a renderer exposed it because the typicalItem that is composed to figure out sizes and the actual first item in the list share the same textFlow.  It actually has nothing to do with useVirtualDisplay other than it was sharing a textFlow.
    It turns out that the TextFlowFactory dispatches damage events every time the textFlow is composed.  Unlike when the flowComposer is used, it always considers the flow damaged.  It was exacerbated by each of the two components having a damage handler for the same textFlow.
    The solution is to use the textFlow generation number.  In the damageHandler if the generation is the last known generation number, assume no changes, and return immediately from the damage handler.
    QE notes: There are 1 TextArea, 6 TextInput and 2 NumericStepper failuers, with or without my changes.  The common link seems to be DispatchKeyEvent.  Most were testing maxChar, displayAsPassword and restrict.  I tested these and they seem to be working correctly.
    Doc notes:
    Bugs: SDK-23002
    Reviewer: Gordon
    Tests run: checkintests, TextArea, TextInput and NumericStepper
    Is noteworthy for integration: no
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-23002
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/RichEditableText.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/RichText.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/supportClasses/RichEditable TextContainerManager.as

    Revision: 10214
    Author:   [email protected]
    Date:     2009-09-13 07:33:58 -0700 (Sun, 13 Sep 2009)
    Log Message:
    This fixes the problem that if two text components share the same textFlow there is an infinite loop involving updateDisplayList -> damageHandler -> invalidateDisplaylist -> back to updateDisplayList.  The bug file was for TextArea which is RET but the same bug was in RichText as well.
    This example with a renderer exposed it because the typicalItem that is composed to figure out sizes and the actual first item in the list share the same textFlow.  It actually has nothing to do with useVirtualDisplay other than it was sharing a textFlow.
    It turns out that the TextFlowFactory dispatches damage events every time the textFlow is composed.  Unlike when the flowComposer is used, it always considers the flow damaged.  It was exacerbated by each of the two components having a damage handler for the same textFlow.
    The solution is to use the textFlow generation number.  In the damageHandler if the generation is the last known generation number, assume no changes, and return immediately from the damage handler.
    QE notes: There are 1 TextArea, 6 TextInput and 2 NumericStepper failuers, with or without my changes.  The common link seems to be DispatchKeyEvent.  Most were testing maxChar, displayAsPassword and restrict.  I tested these and they seem to be working correctly.
    Doc notes:
    Bugs: SDK-23002
    Reviewer: Gordon
    Tests run: checkintests, TextArea, TextInput and NumericStepper
    Is noteworthy for integration: no
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-23002
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/RichEditableText.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/RichText.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/components/supportClasses/RichEditable TextContainerManager.as

  • A few selection of websites after fully loading become blank and start an infinite loop of loading. I reinstalled firefox once already and the problem persists. What can I do?

    A few selection of websites after fully loading become blank and start an infinite loop of loading. I reinstalled firefox once already and the problem persists. What can I do?

    Sorry I do not know what the problem may be. <br />
    If no-one comes up with better ideas of what causes this then my questions and suggestions:
    What do you mean by an infinite loop ? <br />
    The page loads and then goes blank. What exactly happens next, does the page fully load and fully display again before going blank, and repeat this cycle endlessly in the same tab.
    You do say the problem persisted in safe-mode and you had looked at the basic troubleshooting article. Buy that you can stop the problem by disabling javascript.
    * did you disable all plugins - and did you still get the problem then ?
    As you mention disabling javascript stops the problem, have you tried with<br /> Java script enabled but
    * block popups ON
    * load images automatically OFF
    * advanced options - ALL OFF<br /> What happens do you get the problem then or not.
    While on this firefox site if I look at the error console Ctrl+Sift+J or Tools -> Error console If I clear the console content and reload the webpage the error console shows only a couple of messages. YouTube home page give a lot of yellow triangle warnings about 200, but no red warnings, do you get red warnings.
    You could also try on the problem sites eg YouTube changing the permissions with tools -> Page Info | Permissions
    Did you try the Basic Troubeshooting suggestion of making a new profile. (Heeding the warning not to delete settings, otherwise you loose all bookmarks etc) did that help ?

  • Hasmap.put,get infinite loop, 27.6 optimizer problem

    Helo,
    We have a very busy (3000 users) Weblogic Portal and Weblogic Integration instance.
    We found that some times (once a week) weblogic server threads go to infinite loop doing hasmap.get, hashmap put or hashmap remove operations.
    Our developers found that there are synchronization problems with hashmap operations in the portal and wli code, (in 5 classes until today) they patched (synchronized) it and now the instances are stable.
    We contacted oracle support, but they only recommended us some wlw.. setting, none of them worked.
    The strange thing that the code that we patched is existed in weblogic server for years, so I tried to exclude the hasmap class from the optimizer in jrockit.opt file. Now the instances are also stable without the inhouse patches.
    So I suspect theh the jrockit optimizer optimize the hasmap class after some time in a wrong way; how can I find some evidence about it?
    The thead dumps showing only the hasmap operations and very high cpu usage.
    We are on Jrockit 27.6, JVM 1.5, Portal and WLI 9.2MP3
    Regards,
    LJ

    Not sure if it is relevant to the issues you describe in this thread, but a common problem with HashMaps is incorrect (missing) synchronization on concurrent operations. If you do have several threads concurrently accessing a HashMap without synchronization, it might mess up the internal data structures in the HashMap object. This can lead to infiinite loops when trying to iterate through the HashMap at some later time. This problem is not JVM-specific but changes in timing due to different JVM versions, JIT compilation/optimization or different HW etc can cause a previous "stable" program to become "unstable".
    I've seen a number of JRockit support issues related to this problem over the years, and in almost all cases it's been a problem in the Java code (which could be WLS, or the user application).
    Unfortunately it's far from trivial to troubleshoot concurrency issues. One (slow) way of checking your own code is to wrap all HashMaps in a SynchronizedMap. This will slow down your application but if the problem goes away then it's a good indication of the root cause. Not very useful if the problem is in 3rd party code that you don't have the source for, of course. In that case you have to open a ticket with the vendor (Oracle or other 3rd party).
    Cheers,
    Henrik

  • MVC problem - infinite loop?

    I'm going to use a horribly oversimplified example to make my point here, because if I were to describe the actual code I'm looking at, it would take the better part of the afternoon and I'd probably bore you all to tears in the process. So, for the sake of argument, let's assume the following model object:
    public class MyModelObject
      private int a;
      private int b;
      private int c;
      public void setA(int newA)
        a = newA;
        b = newA + SOME_CONSTANT;
        c = newA + SOME_OTHER_CONSTANT;
      public void setB(int newB)
        this.setA(SOME_CONSTANT-newB);
      public void setC(int newC)
        this.setA(SOME_OTHER_CONSTANT-newC);
      public int getA()
        return a;
      public int getB()
        return b;
      public int getC()
        return c;
    }So what we see from this is that the setter for one class property actually changes the value of all three class properties (whether this is good design or not is questionable, but keep in mind this is a horribly simplified example for discussion purposes). The point is that the rules regarding the internal state of MyModelObject are governed entirely within that class - the controller and view don't know about these rules (again, questionable design, but bear with me here).
    Now let's imagine we have a view class that displays a MyModelObject instance and allows the user to change the value of a, b, or c. We also have a controller class that observes the view and responds to changes. When the user modifies the value of, let's say b, the controller will respond to that change by calling the setB() method in MyModelObject. Problem is, now the model and the view are out of synch... someone has to tell the view that the other two class properties have also been modified as a result of calling setB() - whose responsibility is this? Should the model inform the view that something has changed so that the view can redisplay it, or should the view observe the model and automatically redisplay whenever the model is modified?
    More importantly - let's say the controller is observing the view for changes, and the view is observing the model for changes... how do you avoid an infinite loop? For example, the user changes the value of b in the view, which causes the internal state of MyModelObject to be modified, which causes a change in the view, which causes a change in the model, and so on and so forth.
    A twist on the above problem is that it is illegal in some Swing components (JTextPane, for instance) to modify the view while a change notification is in progress... so something like this would throw an IllegalStateException:
    //somewhere in the controller
    public void insertUpdate(DocumentEvent docEvent)
      //update the model
      myModelObject.handleChange(docEvent);
      //now redisplay since the model has changed:
      myTextPane.display(myModelObject);
      // IllegalStateException is raised - Attempt to mutate in notification
    }This fails because you can't change the state of the view component in the event handler for a view change event. How do you get around this using proper MVC architecture? Or am I completely out to lunch here?

    The view shouldn't send events to the controller unless they make sense... For example, it shouldn't fire a change event when the user types in a new value. But only if the user presses enter, or the view loses focus (if this gesture is taken as equivalent).
    So when the change of the view comes from the side-effects of a setter of some property, it should fire no event (so that it will not loop). So it sounds no big problem (if such a distinction of events is easy - it should).

  • RX3870 infinite loop problem

    Hi all
    A week ago i bought the RX3870-T2D512E-OC and now i have problems with it, sometimes while playing games i get a BSOD saying that the ati driver got in a infinite loop, sometimes the image just freezes and i have to restart the PC, and sometimes the VPUrecovery restarts the driver. I have tried different versions of the catalyst driver, reinstalled windows but the results are the same.
    Does anyone have an idea what the problem could be?

    Quote from: Frankenputer on 23-April-08, 11:51:41
    boon25,
    Which Chieftec PSU is that? What specific model?
    It's the GPS-550AB A, here is the chieftec page http://www.chieftec.com/smart-power.html
    I dont think that something's wrong with the PSU because sometimes i can play games for hours without any crashes, they occur randomly

  • BSOD infinite loop problem - Satellite M55

    Many people are getting "infinite loop" error with M55 / ATI 200M.
    Is there a fix for this? My laptop (purchased in May 2006) is worthless...reboots every 2 minutes. Totally unusable.
    There was a post here where the user indicated they found a solution, but the solution was not posted :(
    http://forums.computers.toshiba-europe.com/forums/thread.jspa?threadID=15169
    Please reopen this thread, or post the solution.
    If there is a new driver I'm supposed to use, please post the link (as opposed to just saying "use a new driver").
    Thanks.

    The error appeared around the August / September 2006 timeframe. If you simply boot up the computer, it will happen with a few minutes, just viewing the desktop, with no applications causing the error.
    The computer only has a 90 day warranty. It may have initially occurred within the warranty period, but the Toshiba support rep said it was out of warranty, and they could not help me. The M55 is a relatively inexpensive laptop, so the cost to bring it to a service center is would almost equal the replacement costs. :(
    I installed this Toshiba-provided driver: sm55evideox.exe
    http://www.askiris.toshiba.com/ToshibaSupportSite/search.do?cmd=displayKC&docType=kc&externalId=1158 481xml&sliceId=&dialogID=10312729&stateId=0%200%20 10310682
    This was the most recent (July 2005) driver I could find for the M55-S1001.
    If there is a different driver I should be using, please let me know.
    Maybe I have to uninstall & then reinstall drivers? I don't know....
    The Display properies show the driver is provided by:
    ATI Technologies
    The error message is thus:
    Blue screen...
    "The problem seeems to be caused by the following file: ati2dvag"
    ati2dvag
    Beginning dump of physical memory
    If there is more information or details that may be helpful in a fix or diagnosis, please let me know, and I will post it.

  • Unique Infinite Loop Problem

    Been using iTunes for awhile now and have learned to deal with some of its "quirks" but there is one issue which I am at my ends with.
    I have this issue where after a set amount of time iTunes will crash and studder indefinitely (infinite loop). It seems that this will occur after approximately 12 hrs of continuous playback. My main issue at this point is determining the source of the problem; my sound card, or iTunes. My hunch is iTunes since I can play the same music in Winamp (Latest Version) until I run out of songs to play (takes about 5 days). I have considered the problem as being a possible corrupted audio file however I have determined that this occurs on a very random list of .m4u files. I have not investigated any further into the varying file types of my musical collection however I do know that there are approximately 90% .m4u files, 9% .mp3, and 1% .OTHER.
    Feel free to deck me if this has already been posted... I'm very tired and am not willing to reach for the mouse at this point...
    5:00 AM - Breakfast (Mega Monster) Glug! Glug! Glug!
    5:29 AM - Not Feelin' It (Reaches For NoDoz) Ahhhhhhh...
    OW.. oh god....F@$#!.. that hurts.. my..m mmm m my heart...
    HURL!
    -tW33k
    My Own... Duh!   Windows XP Pro   Dual Core P4 3.0 W/HT OC'D ->3.29; ASUS P4C800E DX Mobo, Creative Audigy 2 ZS Plat., ATI X850 XT, 2 GB Dual Channel PC3200 DDR2, 35 GBx2 10k RAIDStrip

    Missed two points.
    Deadline Branch is Set for 1 minute.
    2) Looked into the SWPA Transaction and my limit is 10,000.

  • A problem with infinite loop

    Hi there! My program has to get data on two species in any order and respond by telling how many years it will take for the species with lower population outnumber the species that starts with higher population. If the species with the smaller population never outnumbers the species with the higher population I'll get an infinite loop. What is the right approach here?
    Thanks.
    public class Species
    private String name1;name2
    private int population1, population2;
    private double growthRate1, growthRate2;
    public void readInput( )
    System.out.println("What is the first species' name?");
    name1 = SavitchIn.readLine( );
    System.out.println("What is the population of the species?");
    population1 = SavitchIn.readLineInt( );
    while (population1 < 0)
    System.out.println("Population cannot be negative.");
    System.out.println("Reenter population:");
    population1 = SavitchIn.readLineInt( );
    System.out.println(
    "Enter growth rate (percent increase per year):");
    growthRate1 = SavitchIn.readLineDouble( );
    ystem.out.println("What is the second species' name?");
    name2 = SavitchIn.readLine( );
    System.out.println("What is the population of
    the species?");
    population2 = SavitchIn.readLineInt( );
    while (population2 < 0)
    System.out.println("Population cannot be negative.");
    System.out.println("Reenter population:");
    population2 = SavitchIn.readLineInt( );
    System.out.println(
    "Enter growth rate (percent increase per year):");
    growthRate2 = SavitchIn.readLineDouble( );
    public void writeOutput( )
    System.out.println("Name of the species' = " + name1);
    System.out.println("Population = " + population1);
    System.out.println("Growth rate = " + growthRate1 + "%");
    System.out.println("Name of the species' = " + name2);
    System.out.println("Population = " + population2);
    System.out.println("Growth rate = " + growthRate2 + "%");
    public void OutnumbersPopulation()
    double max, min;
    int years=0
    if(population1>population2)// this is to determine which population is smaller
    max=population1;
    min=population2;
    else if (population2>population1)
    max=population2;
    min=population1;
    while ((years > 0) && (min <=max))//This could be an infinite loop if min never outnumbers max
    min= (min +
    (growthRate/100) * min);
    max=(max + (growthRate/100) * max);
    years ++;
    System.out.println("The species with the lower population will outnumber the species with higher population
    in" + (years+1) + "years");

    Cross post. original is in "New to Java Technology".

  • .FindText() infinite loop problem

    My company has a need to count how many times certain words are in a PDF document while doing automated testing.  We're using QuickTest Professional and it's programming language is VBScript.  Now I attempted to use the example code from the SDK manual but when I run it it's in an infinite loop.  Once it's gone through the document one time, it jumps back up to the top and counts it again and continue doing this until I either kill the process or kill Acrobat.  My code is attached though it's not much different from the example.  If anyone could help I would be greatly appreciative.
    Option Explicit
    Dim AcroApp, AcroAVDoc
    Dim gPDFPath, bReset, nCount
    gPDFPath = "C:\Documents and Settings\HicksAM\Desktop\Organize Later\DemoDoc.pdf"
    Set AcroApp = CreateObject("AcroExch.App")
    'AcroApp.Show()
    Set AcroAVDoc = CreateObject("AcroExch.AVDoc")
    If AcroAVDoc.Open(gPDFPath, "") Then
         AcroAVDoc.BringToFront()
         bReset = 1 : nCount = 0
         Do While AcroAVDoc.FindText("DRIVER", True, True, bReset)
              bReset = false : nCount = nCount + 1
    '         If Window("Adobe Acrobat").Dialog("Adobe Acrobat").Exist(0) Then
    '               Window("Adobe Acrobat").Dialog("Adobe Acrobat").WinButton("OK").Click
    '               Exit Do
    '          End If
              Wait 0, 200
         Loop
    End If
    AcroApp.CloseAllDocs()
    AcroApp.Exit()
    Print "The word DRIVER was found " & nCount &" times."
    Set AcroApp = Nothing

    This is from the documentation that came with the SDK:
    "Since the JavaScript code runs slowly, it is not suitable for searching through a large PDF file."  I work for an insurance company and the documents can get
    quite lengthy. Not only that, I would need native methods to Acrobat that I can send directly from QTP without having to import specific header/import files.  Just as the example posted in the original post, I could actually get it to search correctly without using any of the SDK files, but it loops infinitely instead of stopping at the end of the PDF document.

  • Infinite loop error after using Java Sun Tutorial for Learning Swing

    I have been attempting to create a GUI following Sun's learning swing by example (example two): http://java.sun.com/docs/books/tutorial/uiswing/learn/example2.html
    In particular, the following lines were used almost word-for-word to avoid a non-static method call problem:
    SwingApplication app = new SwingApplication();
    Component contents = app.createComponents();
    frame.getContentPane().add(contents, BorderLayout.CENTER);I believe that I am accidentally creating a new instance of the gui class repeatedly (since it shows new GUI's constantly and then crashes my computer), possibly because I am creating an instance in the main class, but creating another instance in the GUI itself. I am not sure how to avoid this, given that the tutorials I have seen do not deal with having a main class as well as the GUI. I have googled (a nice new verb) this problem and have been through the rest of the swing by example tutorials, although I am sure I am simply missing a website that details this problem. Any pointers on websites to study to avoid this problem would be appreciated.
    Thanks for your time-
    Danielle
    /** GUI for MicroMerger program
    * Created July/06 at IARC
    *@ author Danielle
    package micromerger;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.swing.JFileChooser;
    import java.lang.Object;
    public class MGui
         private static File inputFile1, inputFile2;
         private static File sfile1, sfile2;
         private static String file1Name, file2Name;
         private String currFile1, currFile2;
         private JButton enterFile1, enterFile2;
         private JLabel enterLabel1, enterLabel2;
         private static MGui app;
         public MGui()
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        System.out.println("About to run create GUI method");
                        app = new MGui();
                        System.out.println("declared a new MGui....");
                        createAndShowGUI();
         //initialize look and feel of program
         private static void initLookAndFeel() {
            String lookAndFeel = null;
         lookAndFeel = UIManager.getSystemLookAndFeelClassName();
         try
              UIManager.setLookAndFeel(lookAndFeel);
         catch (ClassNotFoundException e) {
                    System.err.println("Couldn't find class for specified look and feel:"
                                       + lookAndFeel);
                    System.err.println("Did you include the L&F library in the class path?");
                    System.err.println("Using the default look and feel.");
                } catch (UnsupportedLookAndFeelException e) {
                    System.err.println("Can't use the specified look and feel ("
                                       + lookAndFeel
                                       + ") on this platform.");
                    System.err.println("Using the default look and feel.");
                } catch (Exception e) {
                    System.err.println("Couldn't get specified look and feel ("
                                       + lookAndFeel
                                       + "), for some reason.");
                    System.err.println("Using the default look and feel.");
                    e.printStackTrace();
         // Make Components--
         private Component createLeftComponents()
              // Make panel-- grid layout
         JPanel pane = new JPanel(new GridLayout(0,1));
            //Add label
            JLabel welcomeLabel = new JLabel("Welcome to MicroMerger.  Please Enter your files.");
            pane.add(welcomeLabel);
         //Add buttons to enter files:
         enterFile1 = new JButton("Please click to enter the first file.");
         enterFile1.addActionListener(new enterFile1Action());
         pane.add(enterFile1);
         enterLabel1 = new JLabel("");
         pane.add(enterLabel1);
         enterFile2 = new JButton("Please click to enter the second file.");
         enterFile2.addActionListener(new enterFile2Action());
         pane.add(enterFile2);
         enterLabel2 = new JLabel("");
         pane.add(enterLabel2);
         return pane;
         /** Make GUI:
         private static void createAndShowGUI()
         System.out.println("Creating a gui...");
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("MicroMerger");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //Add stuff to the frame
         //MGui app = new MGui();
         Component leftContents = app.createLeftComponents();
         frame.getContentPane().add(leftContents, BorderLayout.WEST);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
    private class enterFile1Action implements ActionListener
         public void actionPerformed(ActionEvent evt)
              JFileChooser chooser = new JFileChooser();
              int rVal = chooser.showOpenDialog(enterFile1);
              if(rVal == JFileChooser.APPROVE_OPTION)
                   inputFile1 = chooser.getSelectedFile();
                   PrintWriter outputStream;
                   file1Name = inputFile1.getName();
                   enterLabel1.setText(file1Name);
    private class enterFile2Action implements ActionListener
         public void actionPerformed(ActionEvent evt)
              JFileChooser chooser = new JFileChooser();
              int rVal = chooser.showOpenDialog(enterFile1);
              if(rVal == JFileChooser.APPROVE_OPTION)
                   inputFile2 = chooser.getSelectedFile();
                   PrintWriter outputStream;
                   file2Name = inputFile2.getName();
                   enterLabel2.setText(file2Name);
    } // end classAnd now the main class:
    * Main.java
    * Created on June 13, 2006, 2:29 PM
    * @author Danielle
    package micromerger;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Main
        /** Creates a new instance of Main */
        public Main()
         * @param args the command line arguments
        public static void main(String[] args)
            MGui mainScreen = new MGui();
            //mainScreen.setVisible(true);
            /**Starting to get file choices and moving them into GPR Handler:
             System.out.println("into main method");
         String file1Name = new String("");
             file1Name = MGui.get1Name();
         System.out.println("good so far- have MGui.get1Name()");
        }// end main(String[] args)
    }// end class Main

    um, yeah, you definitely have a recursion problem, that's going to create an infinite loop. you will eventually end up an out of memory error, if you don't first get the OS telling you you have too many windows. interestingly, because you are deferring execution, you won't get a stack overflow error, which you expect in an infinite recursion.
    lets examine why this is happening:
    in main, you call new MGui().
    new MGui() creates a runnable object which will be run on the event dispatch thread. That method ALSO calls new MGui(), which in turn ALSO creates a new object which will be run on the event dispatch thead. That obejct ALSO calls new MGui(), which ...
    well, hopefully you get the picture.
    you should never unconditionally call a method from within itself. that code that you have put in the constructor for MGui should REALLY be in the main method, and the first time you create the MGui in the main method as it currently exists is unnecessary.
    here's what you do: get rid of the MGui constructor altogether. since it is the implicit constructor anyway, if it doesn't do anything, you don't need to provide it.
    now, your main method should actually look like this:
    public static void main( String [] args ) {
      SwingUtilities.invokeLater( new Runnable() {
        public void run() {
          MGui app = new MGui();
          app.createAndShowGUI();
    }// end mainyou could also declare app and call the constructor before creating the Runnable, as many prefer, because you would have access to it from outside of the Runnable object. The catch there, though, is that app would need to be declared final.
    - Adam

  • 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);
    }

Maybe you are looking for