RemoveMovieClip() problems

I'm having trouble with removing a movie clip. This is the
area of code in question:
_root.ContentContainer.swapDepths(0);
removeMovieClip(_root.ContentContainer);
_root.createEmptyMovieClip("ContentContainer",
_root.getNextHighestDepth());
buildQuestion(questionNum);
The "ContentContainer" movie clip conains all of the content
on the stage with exception of the menu. When you click on a menu
button, I want any content cleared and rebuilt. This bit of code
works ever-other click. This means that the first click on a menu
item will not remove the movie clip and cause everything else to
break. By clicking another menu item, the ContentContainer movie
clip is removed normally and everything works nicely. Is there
perhaps a problem with removing and creating a movie clip with the
same name? or does it have to do with waiting for the movie clip to
be removed/created before accessing it? Any insight would be
greatly appreciated!

there are several badly coded components. among other
problems, some place their depth at the highest depth allowed by
flash for a removable movieclip (1,048,575).
then when you use _root.getNextHighestDepth() to assign a
depth to a movieclip that you create (like _root.ContentContainer)
that movieclip is placed beyond the range of a removable movieclip.
hence, your problem.
to remedy, don't use components, don't use
_root.getNextHighestDepth() or both. i prefer both.
in particular, i find it easier (less typing) and less
problematic to use a variable (i use dep) to track the depths i use
in flash. i start my projects with dep=0 and everytime i use a
depth, i increment dep immediately.

Similar Messages

  • Flash images.removeMovieClip(); Problem

    So basically im putting together a little flash website and i
    created a photo gallery and put it on a frame seperate from the
    others and i want a button on the first frame to take you
    automatically to the photo gallery. So i did and it worked. I also
    created a little x-out button on the photo gallery so that when you
    click it it takes you back to frame 1 [index]. And it also works
    except the large thumbnails in my gallery follow it home and then
    you just stuck with a big old unwanted picture on your homepage.
    This is the code i put into the frame of the photo gallery::
    Any Thoughts?
    Someone told me to add a images.removeMovieClip(); command
    but that didnt work...was i supposed to put something before
    images.removeMovieClip(); or after it?

    you are adding two movies to your main SWF:
    * images
    * mask
    You should be able to remove either or both of them by using
    removeMoveClip() which is documented here:
    http://livedocs.adobe.com/flash/8/main/00002510.html#wp370720
    To remove images:
    images.removeMovieClip();
    To remove mask:
    mask.removeMovieClip();
    IMPORTANT: The code where you call this may have a different
    scope then the code where you create images and mask. You may need
    to refer to something like this:
    _parent.removeMovieClip();

  • RemoveMovieClip problem

    I have a button to attach a movie called "ColorChipPopUp".
    attachMovie_btn3.onRelease = function(){
    this._root.attachMovie("ColorChipPopUp", "chip", 3);
    _parent.chip._x = 340;
    _parent.chip._y = 200;
    The button (instance name "attachMovie_btn3") is in a movie
    called "corkboard" on scene 1. In the movie, "ColorChipPopUp" I
    have a close button that removes the movie clip from the parent
    movie "corkboard".
    on (release) {
    _root.chip.removeMovieClip();
    Everything works fine until...I want to do when I remove the
    "ColorChipPopUp" movie and go to different frame in the "corkboard"
    movie (instance name is corkboard).
    on (release) {
    _root.chip.removeMovieClip();
    _root.corkboard.gotoAndPlay(146)
    What am i missing in this script
    "_root.corkboard.gotoAndPlay(146)"?
    Thanks Brian

    OK, first thing, ace the 'this._root' from the attachMovie
    call, and use '_parent', you can also pass the x,y parameters
    within a Init Object in the method, as in:
    _parent.attachMovie('ColorChipPopUp', 'chip', 3, {_x:340,
    _y:200});
    ... now a few things I'm not following, I assume that this
    attaches the 'chip' to the main timeline at level 3, but you go on
    to say that your removing the 'chip' from the MC 'corkboard' is
    'corkboard' the name of your swf? because other wise the call
    '_root.chip.removeMovieClip();' is not removing the 'chip' MC from
    the MC 'corkboard' so this is very confusing. Further you go on to
    say that you want to call to 'corkboard' to advance it's timeline
    to 146, well is there a MC named 'corkboard' or did you maybe give
    Scene 1 that name or something, because if the call
    '_root.chip.removeMovieClip();' does what it is suppose to like you
    say is working, there is no 'corkboard' MC, and the call should be:
    _root.gotoAndPlay(146);
    Sorry, just confused ;)

  • [AS 2.0] Problem with removeMovieClip+setInterval

    For this movie, I'm showing a grid of symbols that appear,
    pause, then fade, so I can have people try to identify them quickly
    (for a psych experiment). I have a "Grid" that all of these
    "GridSymbols" are children of (currently using the DepthManager,
    but I'm pretty sure I had the same problem when I used
    getNextHighestDepth).
    I'm using a timer (via setInterval) to be able to dynamically
    set a time for a movie to remain visible on the screen (there is a
    5 frame fade-in, then a setInterval timer on a stop() frame that
    after the time jumps to the fadeout frame). This works great until
    I need to remove all of the currently visible movies to progress to
    a new part of the task that I am creating. The offending code looks
    like this (on frame 6, after the fade):
    stop();
    this.delayAmount = setInterval(goToFade,
    _root.SymbolVisible);
    function goToFade()
    gotoAndPlay("fadeout_frm");
    clearInterval(delayAmount);
    The problem occurs when I remove the Grid (thus removing all
    of the GridSymbols). If however I remove the delayAmount interval
    and simply insert 10 static frames from 6 - 15 the program works
    fine, so I feel confident that it has to do with the interval
    (perhaps maturing after the movie has been removed and then looking
    for the appropriate frame to jump to). Anyone have any idea how to
    fix this? Or perhaps an alternate method of accomplishing the same
    goal?
    Thanks!

    Ok, I've got a solution, though it might not be pretty. I'm
    creating an array to hold the symbol instance names of all of the
    movies that have the internal intervals running:
    symbolIDArray[hPos+vPos*Horiz] =
    CurrentGrid.createChildAtDepth("grid_symbol", DepthManager.kTop);
    Then, when I need to delete, I run this quick loop:
    for (i = 0; i < symbolIDArray.length; i++)
    clearInterval(symbolIDArray
    .delayAmount);
    Once the loop has finished, the movies can be removed
    without problem. :)

  • Simple (?) paths problem

    I have an image gallery consisting of thumbnail buttons,
    which load the external fade in/out files. When the buttons are on
    the main timeline everything works perfectly, but I wanted them to
    be scrollable so I placed them in a MC(main) and now the externals
    won’t load – the scrolling and button actions are fine.
    There are 2 separate container movie clips for the content to
    load into and there’s also a preloader.
    Here’s the buttonAS:
    var bottomcontainer = container1_mc;
    // load image 1 loads the image using startPreload
    image1_btn.onPress = function(){
    startPreload("load/spot.jpg");
    function startPreload(url){
    attachMovie("preloader anim", "preloader_mc", 500, {_x:740,
    _y:454});
    bottomcontainer._alpha = 0;
    bottomcontainer.contents_mc.loadMovie(url);
    bottomcontainer.onEnterFrame = preloadContents;
    I built the site in small chunks and didn’t expect to
    encounter further problems during final assembly; I’m now
    completely baffled! Any suggestions as to what’s wrong?

    Unfortunately, no joy. I tried preloadcontents with and
    without _parent.
    To clarify: the container has a separate script, but I
    didn’t think this would be causing the problem:
    // this is the event handler for each container's
    // onPreloaderComplete event - a custom event invoked
    // in the preloadContents function
    function preloadComplete(){
    // swap the depths of the containers putting the
    // one who just got new content at the top
    container1_mc.swapDepths(container2_mc);
    // check the depths of the 2 containers and assign
    // bottomcontainer to the new lowest container
    if (container1_mc.getDepth() < container2_mc.getDepth()){
    bottomcontainer = container1_mc;
    }else{
    bottomcontainer = container2_mc;
    // remove the preloader animation
    preloader_mc.removeMovieClip();
    // set the onEnterFrame event to fade in this container
    this.onEnterFrame = fadeIn;
    // this function fades in a container
    // once its content has loaded
    // it is to be used with onEnterFrame
    function fadeIn(){
    // if the alpha is less than 100, fade in
    if (this._alpha < 100){
    // increase using a rate of 5
    this._alpha += 5;
    }else{
    // delete the onEnterFrame event handler
    // running this fadeIn method
    delete this.onEnterFrame;
    // set onPreloaderComplete functions (event handlers)
    // for each container to the preloadComplete function
    // when a container is completely loaded, preloadContents
    // will call onPreloaderComplete for the container which
    // will run preloadComplete because of these definitions
    container1_mc.onPreloaderComplete = preloadComplete;
    container2_mc.onPreloaderComplete = preloadComplete;

  • ComboBox insertion problem

    When I add a Flash 8 Combo Box component to this movie, it
    imediately breaks (chokes on the loading of data).
    http://www.scarpanorthamerica.com/cms_caic/register_management_033.fla
    The if I delete the component from the stage and my library,
    then the movie runs fine again.
    If I add this line of code:
    import mx.controls.ComboBox;
    The movie breaks similiarly.

    I solved the problem yesterday. I had to _root.focusManager.removeMovieClip() and, if the controls are properly aligned you can navigate in 4-way flawlessly. My main problem was that the controls weren't aligned, so the player didn't change focus reasonably.
    Anyone can think of another way that doesn't involve murdering the focusManager? Not sure this is the proper way of things...
    Regards

  • Linkage problem : cannot find the linkage instance

    Hello everyone,
    I'm trying to create a linkage to swap movie clip dynamically. I already create a linkage and after my movie clip symbol actuall say Export: contact_idea. But when I try to attachMovie("contact_idea"). It does nothing. Is there anyway that I can test that the linkage is actuall linked?
    Thanks

    Thank you very much for your reply. But I still have the problem.
    This is my situation.
    on my stage _root stage I have a movie clip named "head". In movie clip head also have movieclips, "part", and "MC_Holder" which play simultaneously. In "part" movieclip, I have a button which is supposed to be clicked and play "MC_Holder" movieclip which I have the problem.
    this is my code in my button in "part" movieclip
            _root.head.MC_Holder.gotoAndPlay("48");
            _root.head.MC_Holder.removeMovieClip();
            _root.head.MC_Holder.attachMovie("contact_idea","newidea",this.getNextHighestDepth());
            _root.head.MC_Holder.gotoAndPlay("48");
    _root.head is the movieclip in root which doesn't have any problem calling it.
    "contact_idea" is the linkage in my library, which I stated earlier that I linked it already and it displayed a symbol Export: contact_idea.
    Thank you very much for all of you.

  • Problems with an array (attachMovie)

    I've created a 20 x 20 grid of objects (openCircles). They're set to 'alpha = 0', then 'alpha = 100' on rollover. This works for all of them except for the final one at the coordinate T,20 in the bottom right corner, as I'm not able to rollover over it. To test whether or not they all existed, I set them all to an initial value of 'alpha = 100' and they did all appear, but I'm still unable to rollover the one at T20.
    The other problem is that when an 'openCircle' is clicked, a 'filledCircle' (set up as another grid of invisible objects in the same place) is supposed to appear in its place. That doesn't happen. All of the objects are created and exist, using attachMovie, so it's maybe due to some logical error. See code:-
    I'd be grateful for any help. Many thanks.
    stop();
    //The purpose of this experiment is to locate a trap of oil. Only 30 exploration holes are allowed.
    //Use the grid coordinate to locate the borehole and then plot the depth
    //Drilled is set to false in the 1st(previous) frame
    //Rolling over a grid coordinate will reveal a borehole (open circle).
    //Click on the borehole (open circle) to start drilling
              //open circle will be removed
              //drilled is set to true for that coordinate
              //filled circle will appear in its place
    //set up variables for grid array of open circles (undrilled) and closed circles (drilled)
    var spacing:Number = 5.75;
    var cols:Number = 20; // number of columns in grid
    var rows:Number = 20; // number of rows in grid
    var leftMargin:Number = 154;
    var topMargin:Number = 169;
    var currentRow:Number = 0;
    var currentCol:Number = 0;
    for (i=1; i<=rows; i++) {                                                                                                         
    for (j=1; j<=cols; j++) {                                                                                                                              
              current = attachMovie("openCircle_mc", "openCircle_mc"+i+"_"+j,getNextHighestDepth());
              current._x = leftMargin + ((i-1) * (spacing + current._width));
              current._y = topMargin + ((j-1) * (spacing + current._height));
              current2 = attachMovie("filledCircle_mc", "filledCircle_mc"+i+"_"+j, getNextHighestDepth());
              current2._x = leftMargin + ((i-1) * (spacing + current2._width));
              current2._y = topMargin + ((j-1) * (spacing + current2._height));
              //open circle initially invisible, then visible on rollOver
              current._alpha = 0;
              //filled circles initially invisible
              currentCol2=(current2._x-leftMargin)/(spacing + current2._width);
              currentRow2=(current2._y-topMargin)/(spacing + current2._height);
                                     if (drilled[currentCol,currentRow]==true){
                                                      current2._alpha = 100;
                                                      }else{
                                                                current2._alpha=0;
              //open circle visible on rollover
              current.onRollOver = function() {
                                     this._alpha = 100;
                                     currentCol=(this._x-leftMargin)/(spacing + current._width);
                                     trace("current column ="+currentCol);
                                     currentRow=(this._y-topMargin)/(spacing + current._height);
                                     trace("current row ="+currentRow);
                                     if (drilled[currentCol,currentRow]==false){
                                              trace("Click on the grid point to drill at "+rowLabel[currentRow]+","+colLabel[currentCol]);
                                  }else{
                                              trace("Click on the grid point to review the core at "+rowLabel[currentRow]+","+colLabel[currentCol]);
                                  }     //end 'if-else'
              //open circle invisible on rollout
              current.onRollOut = function() {
                                     this._alpha = 0;
                                     trace("No grid point selected")
              //click on open circle - variable drilled becomes true
              current.onRelease=function(){
                        drilled[currentCol,currentRow]=true;
                        trace(drilled[currentCol,currentRow]);
                        this.removeMovieClip();
    This is an image of the grid showing an 'openCircle' visible when rolled over

    Thanks for the explanation. That was very helpful.
    However, I am having problems with the variables. I did as you suggested though and extended the (grid) layer, but had to create a separate keyframe for the code layer, as that code had to execute first before moving into the next frame. See below (I've also attached the fla, but if you need any more information, please let me know):
    In frame 2 of the animation, if an open circle mc is clicked, that mc is deactivated (removed), drilled becomes true for that coordinate, a filled circle becomes visible in its place and you enter another frame(3) (this is currently just a test frame), to later be used to implement the drilling animation for a clicked coordinate.
    It all seems to be working as it should, until the open circle is clicked and you enter frame 3. See below:
    All the instances of the openCircle mc's are still active in frame 3, so I guess I need to use removeMovieClip(). I know how to do that for a single instance, but howdo I execute that if they're in an array?
    I also don't want any instances of the filledCircles from frame 2 to be visible in frame 3. I'm not sure how to hide them temporarily in frame 3 and then have them visible again in frame 2?
    When I go back to frame 2 (using a back button), all of the filled circles in the array are visible, whereas only the ones that have been previously clicked (drilled = true) should be visible. However, when I return to frame 2 and do a trace to find out which coordinates are set to true/false, it seems that a whole row is now set to (drilled = true), whereas it should just be a single coordinate set to true. Oddly enough, the variable seems to working properly in frame 2 when the code is first executed, but then when I go to frame 3 and then re enter frame 2, it's not working as it should do. Below is the trace code that I've used:
    if (drilled[currentCol,currentRow] == false) {
                                            trace("Click on the grid point to drill at " + rowLabel[currentRow] + "," + colLabel[currentCol]);
                                  } else {
                                            trace("Click on the grid point to review the core at " + rowLabel[currentRow] + "," + colLabel[currentCol]);
    If you could help, I'd be very grateful! Very many thanks.
    http://synergese.co.uk/boreholes15.fla
    Message was edited by: Pippa01
    Sorry, Although the original question was correct, I've just unmarked it as correct. Maybe, I should have started it as a new thread?

  • RemoveMovieClip doesn't work?

    Hi,
    Kindly advise the best way to remove duplicateMovieClip in
    other frames!
    I tried the folowing:
    this.onEnterFrame=function(){
    back1_btn.onRelease = function() {
    gotoAndStop("one");
    unloadMovie("snowflake");
    removeMovieClip("snowflake");
    snowflake.removeMovieClip();
    }

    Why do you have this inside an onEnterFrame event?
    I'm assuming that you created the "snowflake" mc with a
    duplicateMovieClip or
    attachMovieClip method. I think your problem is a scoping
    issue. When you
    defined the button back1_btn function, the reference is from
    inside that
    button. So unless "snowflake" is inside the back1_btn your
    calls won't work
    from there.
    if your "snowflake" movie was created on the same level as
    the back1_btn then
    you should be able to use this:
    back1_btn.onRelease = function() {
    this._parent.snowflake.removeMovieClip();
    // this : refers to the button
    // _parent : refers to the level just above the button
    If it is on a different path than the back1_btn, you will
    need to use the
    correct path to the movieclip before the removeMovieClip
    method will work.
    Tim

  • TextArea cause removeMovieClip to stop working

    Hello all,
    I can't find any documentation on this bug. So I am wondering
    if anyone else has ran into this problem.
    Basically a working line of code:
    removeMovieClip(clip_mc);
    stops working as soon as the textArea component is a) on the
    stage or b) just in the library.
    very odd. well, I don't expect many of you have run into
    this, but its worth a shot anyways.
    cheers.

    My current workaround is to just use unloadMovie, which in
    the scenario im dealing with will work ok.
    But I encourage anyone to recreate this interesting occurance
    by following these steps:
    1. New blank document
    2. Draw a cube on the stage, convert to a movie clip (called
    "cube_mc"), delete it.
    3. in the Library, export your cube movie clip for
    actionscript.
    4. put this code on frame 1:
    _root.createEmptyMovieClip("newClip",_root.getNextHighestDepth());
    newClip.attachMovie("cube_mc","newCube",newClip.getNextHighestDepth());
    removeMovieClip(newClip);
    5. This code will work (i.e. the cube will be loaded, and
    then removed)
    6. Add a component to your library.
    7. The code now ceases to work (at least for me)

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • J2ME problem with threads

    Hi all,
    I would like to ask you for a help. I need to write a small program at my university. I started to write a midlet which function would be to countdown time for sports activities. I woul like to start a new thread - the one that counts down - and at the same time make the main thread sleep. After the "countdown" thread finishes, the main thread wakes up and waits for user input. The problem is that when the "countdown" thread finishes his work, I've got Uncaught exception java/lang/NullPointerException. error and the midlet halts.
    Below you can find the code
    import java.lang.*;
    import java.util.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class intervals extends MIDlet implements CommandListener
    public Display ekran;
    private SweepCanvas sweeper;
    private Form rundy;
    private TextField round0, round1, round2, round3, round4, round5, round6, round7, round8;
    private long czas,x;
    private Command exitCommand;
    private Command addRound;
    private Command delRound;
    private Command start;
    private TextField repeat;
    private Form odliczanie;
    private Alert ostrz;
    Licznik thread;
    String test;
    StringItem test1;
    int parz,i,j,k;
    static int l;
    int ilrund;
    int ilpowt;
    Item sec;
    long sec1;
    public intervals()
        rundy = new Form("Interwa&#322;y sportowe");
        exitCommand = new Command("Wyj&#347;cie", Command.EXIT, 2);
        addRound = new Command("Dodaj","Dodaj rund&#281;", Command.ITEM,1);
        delRound = new Command("Usu&#324;","Usu&#324; ostatni&#261; rund&#281;", Command.ITEM,1);
        start = new Command("Start", Command.ITEM,1);
        odliczanie = new Form("Odliczanie");
        TextField dodaj(TextField kolej)
            kolej=new TextField("Podaj czas (s) rundy "+parz,null, 4, TextField.NUMERIC);//stworzenie nowej instancji do wybierania czasu trwania rundy
            if(rundy.size()==0)
                rundy.insert(rundy.size(),kolej);
                else
                    rundy.insert(rundy.size()-1, kolej);
            return kolej;
        void odliczanie(TextField round)
            monitor m=new monitor();
            k=Integer.parseInt(round.getString());
            ekran.setCurrent(odliczanie);
            thread=new Licznik(k,odliczanie);
            thread.start();
            ekran.setCurrent(rundy);
    public void startApp()// throws MIDletStateChangeException
        rundy.deleteAll();
        repeat = new TextField("Podaj ilo&#347;&#263; powtórze&#324;",null,1,TextField.NUMERIC);
        rundy.addCommand(addRound);
        rundy.addCommand(exitCommand);
        rundy.setCommandListener(this);
        Canvas obrazek = new MyCanvas();
        ekran = Display.getDisplay(this);
        ekran.setCurrent(obrazek);
        czas=System.currentTimeMillis();
        while (System.currentTimeMillis()<czas+1000)
            continue;
        ekran.setCurrent(rundy);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
        notifyDestroyed();
    public void commandAction(Command c, Displayable s)
        if (c == exitCommand)
            destroyApp(false);
            notifyDestroyed();
        else if(c==addRound)
            if(rundy.size()==0)//Sprawdzenie ilo&#347;ci elementów w celu poprawnego wy&#347;wietlania liczby rund w formie
                parz=1;
                else
                parz=rundy.size();
            switch(parz)
                case 1:
                    round0=dodaj(round0);break;
                case 2:
                    round1=dodaj(round1);break;
                case 3:
                   round2= dodaj(round2);break;
                case 4:
                    round3=dodaj(round3);break;
                case 5:
                    round4=dodaj(round4);break;
                default:
                    ostrz=new Alert("Uwaga","Maksymalna liczba rund wynosi 9", null, AlertType.INFO);
                    ostrz.setTimeout(3000);
                    ekran.setCurrent(ostrz);
            if(rundy.size()==1)
                rundy.append(repeat);
                rundy.addCommand(start);
            rundy.addCommand(delRound);
        else if(c==delRound)
            if(rundy.size()!=0)
                rundy.delete(rundy.size()-2);
                if (rundy.size()==1)
                    rundy.deleteAll();
                if(rundy.size()==0)
                    rundy.removeCommand(delRound);
                    rundy.removeCommand(start);
        else if(c==start)
            ilrund=rundy.size()-1;
            if(this.repeat.size()>0)
                ilpowt=Integer.parseInt(this.repeat.getString());
            ekran = Display.getDisplay(this);
            for (i=1; i<=ilpowt;i++)
                odliczanie= new Form("Odliczanie");
                 for (j=0;j<ilrund;j++)
                    switch(j)
                         case 0:
                             odliczanie(round0);
                             break;
                         case 1:
                             odliczanie(round1);
                             break;
                         case 2:
                             odliczanie(round2);
                             break;
                         case 3:
                             odliczanie(round3);
                             break;
                         case 4:
                             odliczanie(round4);
                             break;
                         case 5:
                             odliczanie(round5);
                             break;
                         case 6:
                             odliczanie(round6);
                             break;
                         case 7:
                             odliczanie(round7);
                             break;
                         case 8:
                             odliczanie(round8);
                             break;
    class Licznik extends Thread
        int czas1,k;
        Form forma;
        monitor m;
        public Licznik(int k,Form formap)
            czas1=k;
            forma=formap;
        public synchronized void run()
            while(czas1>0)
                forma.deleteAll();
                forma.append("Czas pozosta&#322;y (s): "+czas1);
                try{Thread.sleep(1000);} catch(InterruptedException e){e.printStackTrace();}
                czas1--;
            if(czas1<=0)
                m.put();
        }and monitor class
    public class monitor
    boolean busy=false;
    synchronized void get()
        if(!busy)
            try
                wait();
            }catch(InterruptedException e){e.printStackTrace();}
        notify();
    synchronized void put()
        if(busy)
            try
            wait();
            }catch(InterruptedException e){e.printStackTrace();}
        busy=true;
        notify();
    }Can anybody help me with this?

    Groovemaker,
    Your Licznik class has a member m of type monitor, which has not been instantiated (in other words is null) hence, when calling m.put() you get NullPointerException. Please also mind, that using Thread.sleep(1000) is not an accurate way of measuring time.
    If I may, please use recommended for Java class naming conventions - some of your names use lower case, while other don't which is confusing to the reader.
    Daniel

  • Problem with threads within applet

    Hello,
    I got an applet, inside this applet I have a singleton, inside this singleton I have a thread.
    this thread is running in endless loop.
    he is doing something and go to sleep on and on.
    the problem is,
    when I refresh my IE6 browser I see more than 1 thread.
    for debug matter, I did the following things:
    inside the thread, sysout every time he goes to sleep.
    sysout in the singleton constructor.
    sysout in the singleton destructor.
    the output goes like this:
    when refresh the page, the singleton constructor loading but not every refresh, sometimes I see the constructor output and sometimes I dont.
    The thread inside the singleton is giving me the same output, sometime I see more than one thread at a time and sometimes I dont.
    The destructor never works (no output there).
    I don't understand what is going on.
    someone can please shed some light?
    thanks.
    btw. I am working with JRE 1.1
    this is very old and big applet and I can't convert it to something new.

    Ooops. sorry!
    I did.
         public void start() {
         public void stop() {
         public void destroy() {
              try {
                   resetAll();
                   Configuration.closeConnection();
                   QuoteItem.closeConnection();
              } finally {
                   try {
                        super.finalize();
                   } catch (Throwable e) {
                        e.printStackTrace();
         }

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

Maybe you are looking for

  • Control Block - Preventing creation of new record

    hi, i have a control block with two text fields. i do not want new record created for this block when the down key is pressed. How do i do that ?

  • [solved] Conky docking problem.

    Sorry for my poor English. I hope you can understand what I say. I want to make my conky stay at bottom like a panel. So I try this in my .conkyrc: own_window yes own_window_transparent no own_window_type dock alignment bottom_middle But the problem

  • Problem installing external monitor

    CT, Thanks for your reply.  (I can't find the way to reply to your message within the original discussion).  I read the manual you referred me to.  I have to say, I have done precisely what the manual is directling.  When I close the Macbook, I don't

  • Picking up only committed rows

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

  • Why am I being ask to purchase skype credit to sen...

    I have a premium subscription and since i signed up this was included. it is now telling me that i need to purchase credit for sKype texting, why?