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

Similar Messages

  • Throws infinite-loop error after cycline through Vector - HELP!!!

    public void paint(Graphics g) {
    FontMetrics fm = g.getFontMetrics();
    xpos = (getSize().width - fm.stringWidth(((String[])parseVector.elementAt(kount))[1])) / 2;
    if (ypos >= getSize().height || ypos <= 0) {
    g.drawString("", 0, 0); // CLEAR THE APPLET
    ypos = getSize().height;
    if (kount <= parseVector.size()) {
    kount++;
    } else {
    kount = 0;
    g.drawString(((String[])parseVector.elementAt(kount))[1], xpos, ypos);
    class ScrollNews implements Runnable {
    public void run() {
    while (true) {
    ypos = ypos - 1;
    ParseNews.this.repaint();
    try {
    Thread.sleep(50);
    } catch (InterruptedException e) {}
    I don't know why this breaks after working one time through the Vector parseVector, what am I missing????
    Phil

    public void paint(Graphics g) {
    FontMetrics fm = g.getFontMetrics();
    xpos = (getSize().width -
    fm.stringWidth(((String[])parseVector.elementAt(kount))
    1])) / 2;
    if (ypos >= getSize().height || ypos <= 0) {
    g.drawString("", 0, 0); // CLEAR THE APPLET
    ypos = getSize().height;
    if (kount <= parseVector.size()) {
    kount++;
    } else {
    kount = 0;
    g.drawString(((String[])parseVector.elementAt(kount))[
    ], xpos, ypos);
    class ScrollNews implements Runnable {
    public void run() {
    while (true) {
    ypos = ypos - 1;
    ParseNews.this.repaint();
    try {
    Thread.sleep(50);
    } catch (InterruptedException e) {}
    I don't know why this breaks after working one time
    through the Vector parseVector, what am I missing????
    PhilI think your problem is here:
    while (true) {You have an infinite loop - how will the while loop ever be false?

  • CBS error after configuring java 1.5 for CE builds

    Hi,
    I have some trouble with building my old projects on the CBS when I try to configure the CBS so that it can build java 1.5 applications. The guide I did use to configure the CBS was the "Setup_an_NWDI_Track_for_Composition_Environment_Developments.pdf".
    There were only two things to do to change the CBS service:
    I changed the following things in the Visual Administrator:
    the 'BUILD_TOOL_JDK_HOME' from C:\j2sdk1.4.2_14-x64 to 'C:\jdk1.5.0_17-x64'
    the 'JDK_HOME_PATH' from 'JDK1.3.1_HOME=C:\j2sdk1.4.2_14-x64;'
    to 'JDK1.3.1_HOME=C:\j2sdk1.4.2_14-x64;default=C:\j2sdk1.4.2_14-x64;JDK1.5.0_HOME=C:\jdk1.5.0_17-x64'
    after that I get the following error message when I try to build an old project:
    Change request state from PROCESSING to FAILED
    Error! The following problem(s) occurred during request processing:
    Error! The following error occurred during request processing:An I/O error occurred on attempt to start an external process to perform the build. The arguments used the start the process are as follows:
    Maybe someone had the same experience?
    regards
    Carsten

    Hi,
    I have some trouble with building my old projects on the CBS when I try to configure the CBS so that it can build java 1.5 applications. The guide I did use to configure the CBS was the "Setup_an_NWDI_Track_for_Composition_Environment_Developments.pdf".
    There were only two things to do to change the CBS service:
    I changed the following things in the Visual Administrator:
    the 'BUILD_TOOL_JDK_HOME' from C:\j2sdk1.4.2_14-x64 to 'C:\jdk1.5.0_17-x64'
    the 'JDK_HOME_PATH' from 'JDK1.3.1_HOME=C:\j2sdk1.4.2_14-x64;'
    to 'JDK1.3.1_HOME=C:\j2sdk1.4.2_14-x64;default=C:\j2sdk1.4.2_14-x64;JDK1.5.0_HOME=C:\jdk1.5.0_17-x64'
    after that I get the following error message when I try to build an old project:
    Change request state from PROCESSING to FAILED
    Error! The following problem(s) occurred during request processing:
    Error! The following error occurred during request processing:An I/O error occurred on attempt to start an external process to perform the build. The arguments used the start the process are as follows:
    Maybe someone had the same experience?
    regards
    Carsten

  • The dreaded "Infinite Loop" error

    I get a "Serious error.. The Driver for the display was unable to complete drawing operation..blah..blah.. The display driver for nvidia Geforce 4 Ti 4200 with AGP 8X seems responsible....
    The log in windows sez a infinite loop error...blah..blah..
    Anyone have any suggestions?
    Thanx
    Specs
    Enermax 350w PSU
    +3.3V=32A
       +5V=32A
     +12V=17A
        -5V=1A
       -12V=1A
    MSI 865 PE Neo2 L BIOS 1.5/Intel chipset 5.0.1007
    2.4GHZ P4 533FSB
    2X256MB Infineon DDR333 (Using non dual channel)
    80 Gb WD JB
    MSI Geforce 4 Ti 4200/ nvidia 52.16
    Sound Blaster X-Gamer
    LG DVD ROM
    LG 52x32x52
    DirectX9b
    Clean Install Windows XP & Service Pack.
    Idle cpu:32C Load:48C
    Bios settings on default slow

    What is fastwrite (MB or video card?) and can you disable it any way besides buying s/w? I've looked all through my BIOS and Detonator setup, can't find this anywhere.
    My reboots are back.

  • MS-6390 and Radeon 9200SE "infinite loop" error

    I recently installed a radeon 9200SE PCI graphics card, and after about a week of perfect operation I began getting the "infinite loop" error. I've tried every fix I can find and nothing works, and upgrading my motherboard isnt an option since I can't afford it.
    Anyone have any ideas as to how I can fix this?

    tried another pci slot with it?

  • MSI FX5200 Infinite loop error

    Hi I’ve changed the PSU to see if this was the problem with the infinite loop error I’m getting. The PSU is AMD recommended or that is what it says on the box. How ever I fitted the PSU and re-booted the PC did a few things and them started 3DMARK03 and I was back in the infinite loop.
    // Watchdog Event Log File
    LogType: Watchdog
    Created: 2004-04-27 14:48:28
    TimeZone: 0 - GMT Standard Time
    WindowsVersion: XP
    EventType: 0xEA - Thread Stuck in Device Driver
    // The driver for the display device got stuck in an infinite loop. This
    // usually indicates a problem with the device itself or with the device
    // driver programming the hardware incorrectly. Please check with your
    // display device vendor for any driver updates.
    EaRecovery: 1
    ShutdownCount: 96
    Shutdown: 0
    EventCount: 9
    BreakCount: 9
    BugcheckTriggered: 1
    DebuggerNotPresent: 1
    DriverName: nv4_disp
    EventFlag: 1
    DeviceClass: Display
    DeviceDescription: NVIDIA GeForce FX 5200
    HardwareID: PCI\VEN_10DE&DEV_0322&SUBSYS_91901462&REV_A1
    Manufacturer: NVIDIA
    DriverFixedFileInfo: FEEF04BD 00010000 0006000E 000A1628 0006000E 000A1628 0000003F 00000008 00040004 00000003 00000004 00000000 00000000
    DriverCompanyName: NVIDIA Corporation
    DriverFileDescription: NVIDIA Compatible Windows 2000 Display driver, Version 56.72
    DriverFileVersion: 6.14.10.5672
    DriverInternalName: nv4_disp.dll
    DriverLegalCopyright: (C) NVIDIA Corporation. All rights reserved.
    DriverOriginalFilename: nv4_disp.dll
    DriverProductName: NVIDIA Compatible Windows 2000 Display driver, Version 56.72
    DriverProductVersion: 6.14.10.5672
    I get this error with three different drivers for the video card MSI the one that came with the card NVIDIA’S latest drivers and the latest drivers on the MSI web site.

    how many amps at plus 12v
     Memtest86

  • How to show error message using java.awt?

    How to show error message using java.awt?
    Which is the class corresponding to the JOptionPane?
    Or I need to use Frame ?

    No, JOptionPane is swing!
    You would have to create your own frame, put your message in it, then show it.

  • Sim card error after using pandora

    I'm getting frequent 'sim not installed' errors after using Pandora app. Anybody else having an issue like that??

    I agree...start with the SIM card first...if that doesn't fix it then pop into the closest Apple Store...

  • My ipad is on an infinite loop.  I used ios7 for a few days and then did updates on some of my apps. that's when the infinite loop started.  I have tried pressing the power and home button at the same time, but it doesn't work. Please help!

    my ipad is on an infinite loop.  I used ios7 for a few days and then did updates on some of my apps. that's when the infinite loop started.  I have tried pressing the power and home button at the same time, but it doesn't work. Please help!
    I even tried some hints posted for ios6 (turn off Ipad, holding home button and plugging in power cord at the same time and then releasing the home button)
    I did manage to get a different screen that shows the itunes icon and a power cord, but nothing happens.

    You were on the right track. You got the connect to iTunes screen and you ended to use iTujes to restore your iPad. Try recovery mode again.
    Recovery Mode Instructions
    Disconnect the USB cable from the iPad, but leave the other end of the cable connected to your computer's USB port.
    Turn off iPad: Press and hold the Sleep/Wake button for a few seconds until the red slider appears, then slide the slider. Wait for iPad to turn off.
    If you cannot turn off iPad using the slider, press and hold the Sleep/Wake and Home buttons at the same time. When the iPad turns off, release the Sleep/Wake and Home buttons.
    While pressing and holding the Home button, reconnect the USB cable to iPad. When you reconnect the USB cable, iPad should power on.
    Continue holding the Home button until you see the "Connect to iTunes" screen. When this screen appears you can release the Home button.
    If necessary, open iTunes. You should see the recovery mode alert that iTunes has detected an iPad in recovery mode.
    Use iTunes to restore iPad.

  • After using the internal mic for the first time I am getting a buzzing feedback from my audio output

    After using the internal mic for the first time I am getting a buzzing feedback from my audio output

    Go to System Preferences Sound Input and adjust the volume level down by dragging the slider to the left. With an audio app like Logic there is an option for input monitoring when recording so there might be a feedback loop if the volume is set too high. Garage Band works in a similar way. Always be careful when using headphones as the noise can be frightful and cause hearing damage. 

  • Using Java to dev for Revo

    Hi,
    I would like to use Java to develop for a Revo (EPOC Symbian OS). Does anyone have any ideas about were I could look for support? Does anyone know if it is possible?
    Thx in advance,
    Matthew

    http://www.google.com/search?q=java+revo

  • Anyone having battery issues on iphone 4 after using Garmin 2.0 for a time?, Anyone having battery issues on iphone 4 after using Garmin 2.0 for a time?

    Anyone having battery issues on iphone4 after using Garmin 2.0 for a while?

    Hi mate. I'm afraid I haven't got a solution, but just wanted to say that I am having the exact same problem in my Lexus. I have an iPhone 5 which was paired and working perfectly while running iOS 6 and then iOS 6.0.1. But I was having all sorts of wifi problems (this is my second iPhone 5 as Apple replaced the first one but I've still got the same wifi issues!) so I had hoped 6.0.2 would fix these bugs. But - as you've found too - it's broken by Bluetooth connection to my car!
    I too had tried the same things as you : deleting the profiles etc. but it just won't pair!
    If anyone has a solution please help!!

  • I already have flashplayer on my mac. I have been using online video tutorials for learning, but suddenly all my YouTube vodeos say "plug-in blocked". I follow the instructions for installing or updating, but nothing has helped. I have looked everywhere i

    I already have flashplayer on my mac. I have been using online video tutorials for learning, but suddenly all my YouTube vodeos say "plug-in blocked". I follow the instructions for installing or updating, but nothing has helped. I have looked everywhere in Safari help with no success. How can I restore this plug-in, PLEASE?
    Austin Moore
    Knoxville, Tennessee

    I already have flashplayer on my mac. I have been using online video tutorials for learning, but suddenly all my YouTube vodeos say "plug-in blocked". I follow the instructions for installing or updating, but nothing has helped. I have looked everywhere in Safari help with no success. How can I restore this plug-in, PLEASE?
    Austin Moore
    Knoxville, Tennessee

  • Infinite Loop Error - How to Remove?

    Only my "home page" will display in WampServer's Localhost, which I am using for my "testing site" in Dreamweaver CS5. All other pages in my website cannot be loaded by IE8 or IE9. Firefox and Chrome report that all webpages (except my "home page" ) have a "Redirect Loop" which prevents them from being loaded, and this is due to links which continuously loop between the same pages.
    QUESTION: How can I fix this (without starting all over to build my website)?
    I am using dynamic webpages with a template, all of which have the "php" extension. I started with HTML webpages and template, and then converted them to "php". They worked well until some time after I added a Login Form on my home page, with Dreamweaver's "User Authentication" in Server Behaviors. The "login" and "password protected" webpages worked for a while. But now it seems like the "Redirect Loop" error may be related to my "go to page if login fails".
    It may or may not be related, but around the same time my Infinite Loop problem started, the "Editable Region" of my home page stopped displaying the formating and background colour in "Design" view in Dreamweaver.  However, they do display properly in Dreamweaver's "Live View" and in WampServer's "Localhost".
    Any all help will be appreciated.

    Thank you for your reply, Nick.  I could not find the code segments which you suggested.
    I have included a link to show the text in my page, "about_us.php", which is one of the several pages I am having trouble with.
    http://www.sunisandsfl.com/text_file_from_about_us_php.html
    This is one of my "Non password-protected" pages. When I load "about_us.php" in Dreamweaver's "Design" view, there is an Error Message above the webpage which says, "An unknown error occurred while discovering dynamically-related files." The only files shown in the "Related files" bar are "Source Code", "conndbss.php" (my database connection file), and "main_sunisands.css".
    I have not yet uploaded any of my dynamic webpages to my live site (www.sunisandsfl.com).

  • How do I escape a jCarousel infinite loop error?

    Using my iPad I went to United.com to book a flight.  I recieved a "jCarousel:No width/hight set for items. This will cause an infinite loop. Aborting ..." error message with only and "OK" button to proceed. Pushing OK only leads to the error repeating. Tried everything to escape the page after pushing OK but nothing seems to work.  Now I'm in an infinite look with the error message.  Relauching safari brings up the same page and error message.  How can I tell safari not to lauch this page or to start on some other page rather than defaulting to the last page visitied?  

    I had they same issue with United. I attempted to clear the cache and it did not help.
    This is what I did to exit the webpage
    1) Disconnect from wifi connection by turning it off
    2) Clear the cache, cookies and history (not sure if this is necessary, but it couldn't hurt)
    3) Power off
    4) when you turn it back on, launch safari and it won't be able to connect.
    5) Kill the window
    6) Enjoy web browsing :)

Maybe you are looking for