Timer Problem

Discussion in 'Programming' started by ellias2007, Oct 20, 2011.

  1. #1
    Hi every one,
    in order to make a method to make a nice transition to any swing item like JPanel or JButton or others, i made the following method :




    public static void MoveTo(final Container Cnt,final int fX,final int fY,final int Slow) {

    MyActionListener = new ActionListener()
    {
    int initialX=Cnt.getX();
    int initialY=Cnt.getY();
    int DeltaX=fX-initialX;
    int DeltaY=fY-initialY;
    public void actionPerformed(ActionEvent actionEvent) {
    Cnt.setLocation(initialX + (int)(DeltaX*Math.sin(Counter*Math.PI/(2*Slow))) , initialY + (int)(DeltaY*Math.sin(Counter*Math.PI/(2*Slow))) );
    Counter++; if (Counter>=Slow) { //Cnt.setLocation(fX,fY);
    Counter=0;
    MyTimer.stop();
    }
    }
    };
    MyTimer = new javax.swing.Timer(0, MyActionListener); //0 milliSeconds as Delay ....
    MyTimer.start();
    }



    But when i use it i face a Crazy problem :
    if i call it and wait it to complete its motion : No Problem...
    BUT if the user calls it and BEFORE ending its motion the user again calls it, a CRAZY motion occurs....
    i have an idea of the problem reason : i call it again then the Conter and may be Mytimer and others are double-used....
    But i don't have an idea about any SOLUTION ....
    Someone has a solution or other idea ...
    Many thanks
     
    Solved! View solution.
    ellias2007, Oct 20, 2011 IP
  2. ellias2007

    ellias2007 Greenhorn

    Messages:
    19
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #2
    Any idea Please !?
     
    ellias2007, Oct 21, 2011 IP
  3. #3
    you can use a bool variable
    and when function is called set it to false after executing function set value to true

    so it will solve your problem
     
    rajpk, Oct 21, 2011 IP
  4. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #4
    To expand on what rajpk said, if the boolean is false when you enter the method, return immediately.

    BTW, this is known ads a non-re-entrant method (or function) - it can't be run more than once at the same time. If you generate the variable names on the fly, you won't have the problem. (Look up using variable variable names.)
     
    Rukbat, Oct 21, 2011 IP