Solved

About Thread.sleep and throws InterruptedException

Posted on 2004-10-29
390 Views
Last Modified: 2010-05-18
I am writing a Java Applet which requires to have one second of delay before repaint(). Now, I, of course, thought about using Thread.sleep(). However, the problem now is that I don't know where should I put the throws InterruptedException statement. In an application, it is after the public static void main(String args[]).

I tried to put it in the actionPerformed method and use the try-catch statement but it went into an infinite loop. I wonder where should I add the throws InterruptedException in an applet?

Thanks!
0
Question by:UltimateApocalypse
    13 Comments
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    Why don't you use Timers instead of Threads
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    in paint method call the timer and in timer object, do what ever you want
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    may I see your code??
    0
     

    Author Comment

    by:UltimateApocalypse
    This applet draws a 11 x 11 grid with a red dot in the center. Once the button is clicked, the dot starts to randomly move on the grid until it has moved 50 times or it has reached the edge of the grid. Now, because it does the repaint() so fast that I am not able to see each of the individual movements; therefore, I think I need a delay of some kind in the actionPerformed() method to slow the repaint() process.

    /* The following two lines import the
       the appropriate library file required
       for this lab.
    */
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import java.util.*;

    public class Lab06Part3 extends Applet implements ActionListener
    {
        Button Start;
        boolean StartFlag = false;
        final int DefaultCoordinate = 70;
        Random Generator = new Random(); //Random number generator

        int StepCounter, TotalDistance, RowCounter, ColumnCounter;
        int XCoordinate = DefaultCoordinate;
        int YCoordinate = DefaultCoordinate;
        int BlockWidth = 20;
        int StreetWidth = 100;
        int DotWidth = BlockWidth / 2;
        int DotXCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;
        int DotYCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;

        public void init ()
        {
            Start = new Button ("Start");
            add(Start);
            Start.addActionListener(this);
        }

        public void paint (Graphics g)
        {
            DrawGrid (g);
            DrawDot (g);

            if (CheckBorder() || StepCounter >= 50)
            {
                g.drawString ("You have traveled " + StepCounter * StreetWidth + " meters.", 10, 20);
                g.drawString ("DotXCoordinate = " + (DotXCoordinate + DotWidth / 2), 10, 35);
                g.drawString ("DotYCoordinate = " + (DotYCoordinate + DotWidth / 2), 10, 50);

                if (CheckBorder())
                {
                    g.drawString ("You made it in " + StepCounter + " steps.", 10, 65);
                }
                else
                {
                    g.drawString ("Too bad!! You did not make it.", 10, 65);
                }
            }
        }

        public void DrawGrid (Graphics g)
        {
            g.setColor (Color.black);

            XCoordinate = DefaultCoordinate;
            YCoordinate = DefaultCoordinate;

            for (RowCounter = 0; RowCounter < 11; RowCounter++)
            {
                g.drawLine(XCoordinate, YCoordinate, XCoordinate + BlockWidth * 10, YCoordinate);
                YCoordinate += BlockWidth;
            }

            XCoordinate = DefaultCoordinate;
            YCoordinate = DefaultCoordinate;

            for (ColumnCounter = 0; ColumnCounter < 11; ColumnCounter++)
            {
                g.drawLine(XCoordinate, YCoordinate, XCoordinate, YCoordinate + BlockWidth * 10);
                XCoordinate += BlockWidth;
            }

            return;
        }

        public void DrawDot (Graphics g)
        {
            g.setColor (Color.red);
            g.fillOval (DotXCoordinate, DotYCoordinate, DotWidth, DotWidth);

            return;
        }

        /* Generates a random number between 0 and 3 which is
           used to pick the direction for the next movement.
        */
        public void PickDirection ()
        {
            switch (Generator.nextInt(4))
            {
                case 0:
                    DotYCoordinate -= BlockWidth;
                    break;

                case 1:
                    DotXCoordinate += BlockWidth;
                    break;

                case 2:
                    DotYCoordinate += BlockWidth;
                    break;

                case 3:
                    DotXCoordinate -= BlockWidth;;
                    break;

                default:
            }

            return;
        }

        /* This method checks to see if the person has reached
           the edge of the town. It checks the coordinates of
           the dot against the coordinates of the grid.
        */
        public boolean CheckBorder ()
        {
            /* Default is false unless the check turns out to be true */
            boolean Result = false;

            if (DotXCoordinate < DefaultCoordinate ||
                DotXCoordinate + DotWidth > DefaultCoordinate + BlockWidth * 10 ||
                DotYCoordinate < DefaultCoordinate ||
                DotYCoordinate + DotWidth > DefaultCoordinate + BlockWidth * 10)
            {
                Result = true;
            }

            return Result;
        }

        public void actionPerformed(ActionEvent e)
        {
            /* Toggle the flag, if it has started
               stop it; otherwise, start it.
            */
            if (StartFlag)
            {
                StartFlag = !StartFlag;
                StepCounter = 0;
                Start.setLabel("Start");
                DotXCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;
                DotYCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;
                repaint();
            }
            else
            {
                while (!CheckBorder() && StepCounter < 50)
                {
                    PickDirection();
                    repaint();
                    StepCounter++;

                }

                StartFlag = !StartFlag;
                Start.setLabel("Reset");

            }

            return;
        }
    }
    0
     

    Author Comment

    by:UltimateApocalypse
    I am just a starter, the Timer option seems to be a lot more complicated than the Thread.sleep() option. ^_^

    Thanks!!
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    You will get some idea from following


    /* The following two lines import the
       the appropriate library file required
       for this lab.
    */
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import java.util.*;

    public class Lab06Part3 extends Applet implements ActionListener
    {
        Button Start;
        boolean StartFlag = false;
        final int DefaultCoordinate = 70;
        Random Generator = new Random(); //Random number generator

        int StepCounter, TotalDistance, RowCounter, ColumnCounter;
        int XCoordinate = DefaultCoordinate;
        int YCoordinate = DefaultCoordinate;
        int BlockWidth = 20;
        int StreetWidth = 100;
        int DotWidth = BlockWidth / 2;
        int DotXCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;
        int DotYCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;

        public void init ()
        {
            Start = new Button ("Start");
            add(Start);
            Start.addActionListener(this);
        }

        public void paint (Graphics g)
        {
           
    //            DrawGrid (g);
      //      DrawDot (g);

            if (CheckBorder() || StepCounter >= 50)
            {
                g.drawString ("You have traveled " + StepCounter * StreetWidth + " meters.", 10, 20);
                g.drawString ("DotXCoordinate = " + (DotXCoordinate + DotWidth / 2), 10, 35);
                g.drawString ("DotYCoordinate = " + (DotYCoordinate + DotWidth / 2), 10, 50);

                if (CheckBorder())
                {
                    g.drawString ("You made it in " + StepCounter + " steps.", 10, 65);
                }
                else
                {
                    g.drawString ("Too bad!! You did not make it.", 10, 65);
                }
            }
        }

        public void DrawGrid (Graphics g)
        {
            g.setColor (Color.black);

            XCoordinate = DefaultCoordinate;
            YCoordinate = DefaultCoordinate;

            for (RowCounter = 0; RowCounter < 11; RowCounter++)
            {
                g.drawLine(XCoordinate, YCoordinate, XCoordinate + BlockWidth * 10, YCoordinate);
                YCoordinate += BlockWidth;
            }

            XCoordinate = DefaultCoordinate;
            YCoordinate = DefaultCoordinate;

            for (ColumnCounter = 0; ColumnCounter < 11; ColumnCounter++)
            {
                g.drawLine(XCoordinate, YCoordinate, XCoordinate, YCoordinate + BlockWidth * 10);
                XCoordinate += BlockWidth;
            }

            return;
        }

        public void DrawDot (Graphics g)
        {
            g.setColor (Color.red);
            g.fillOval (DotXCoordinate, DotYCoordinate, DotWidth, DotWidth);

            return;
        }

        /* Generates a random number between 0 and 3 which is
           used to pick the direction for the next movement.
        */
        public void PickDirection ()
        {
            switch (Generator.nextInt(4))
            {
                case 0:
                    DotYCoordinate -= BlockWidth;
                    break;

                case 1:
                    DotXCoordinate += BlockWidth;
                    break;

                case 2:
                    DotYCoordinate += BlockWidth;
                    break;

                case 3:
                    DotXCoordinate -= BlockWidth;;
                    break;

                default:
            }

            return;
        }

        /* This method checks to see if the person has reached
           the edge of the town. It checks the coordinates of
           the dot against the coordinates of the grid.
        */
        public boolean CheckBorder ()
        {
            /* Default is false unless the check turns out to be true */
            boolean Result = false;

            if (DotXCoordinate < DefaultCoordinate ||
                DotXCoordinate + DotWidth > DefaultCoordinate + BlockWidth * 10 ||
                DotYCoordinate < DefaultCoordinate ||
                DotYCoordinate + DotWidth > DefaultCoordinate + BlockWidth * 10)
            {
                Result = true;
            }

            return Result;
        }

        public void actionPerformed(ActionEvent e)
        {
            /* Toggle the flag, if it has started
               stop it; otherwise, start it.
            */
            if (StartFlag)
            {
                StartFlag = !StartFlag;
                StepCounter = 0;
                Start.setLabel("Start");
                DotXCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;
                DotYCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;
                repaint();
            }
            else
            {
                while (!CheckBorder() && StepCounter < 50)
                {
                    PickDirection();
                            try
                            {
                            Graphics g=getGraphics();
                            repaint();
                            DrawGrid(g);
                            DrawDot(g);
                            Thread.sleep(1000);
                            }
                            catch(Exception ex)
                            {
                            }

                    StepCounter++;
                }

                StartFlag = !StartFlag;
                Start.setLabel("Reset");

            }

            return;
        }
    }
    0
     
    LVL 92

    Expert Comment

    by:objects
    you need to move the dot from a seperate thread.
    0
     

    Author Comment

    by:UltimateApocalypse
    Thanks for the help there. One more question though. As I understand, in the above code. the repaint() gets called first to "clear" the applet window. Then DrawGrid(g) and DrawDot(g) get called to draw the grid and the dot on the new location. Which means,  there should only be one dot present on the window. However, as I run it, the dot actually leaves a track behind. It seems to me that the repaint() did nothing there since it is supposed to clear the last dot before drawing the new one. But it did not do that.
    0
     
    LVL 92

    Expert Comment

    by:objects
    no repaint() says that the applet should be repainted, resulting in a call to paint()
    to get rid of the trail, you need to repaint the background before painting the dot.
    0
     
    LVL 14

    Accepted Solution

    by:
    /* The following two lines import the
       the appropriate library file required
       for this lab.
    */
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import java.util.*;

    public class Lab06Part3 extends Applet implements ActionListener
    {
        Button Start;
        boolean StartFlag = false;
        final int DefaultCoordinate = 70;
        Random Generator = new Random(); //Random number generator

        int StepCounter, TotalDistance, RowCounter, ColumnCounter;
        int XCoordinate = DefaultCoordinate;
        int YCoordinate = DefaultCoordinate;
        int BlockWidth = 20;
        int StreetWidth = 100;
        int DotWidth = BlockWidth / 2;
        int DotXCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;
        int DotYCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;

        public void init ()
        {
            Start = new Button ("Start");
            add(Start);
            Start.addActionListener(this);
        }

          private boolean first=true;

        public void paint (Graphics g)
        {
           

            if (CheckBorder() || StepCounter >= 50)
            {
                                  

                g.drawString ("You have traveled " + StepCounter * StreetWidth + " meters.", 10, 20);
                g.drawString ("DotXCoordinate = " + (DotXCoordinate + DotWidth / 2), 10, 35);
                g.drawString ("DotYCoordinate = " + (DotYCoordinate + DotWidth / 2), 10, 50);

                if (CheckBorder())
                {
                    g.drawString ("You made it in " + StepCounter + " steps.", 10, 65);
                }
                else
                {
                    g.drawString ("Too bad!! You did not make it.", 10, 65);
                }
            }
        }



        public void DrawGrid (Graphics g)
        {
         
                g.setColor (Color.black);

            XCoordinate = DefaultCoordinate;
            YCoordinate = DefaultCoordinate;

            for (RowCounter = 0; RowCounter < 11; RowCounter++)
            {
                g.drawLine(XCoordinate, YCoordinate, XCoordinate + BlockWidth * 10, YCoordinate);
                YCoordinate += BlockWidth;
            }

            XCoordinate = DefaultCoordinate;
            YCoordinate = DefaultCoordinate;

            for (ColumnCounter = 0; ColumnCounter < 11; ColumnCounter++)
            {
                g.drawLine(XCoordinate, YCoordinate, XCoordinate, YCoordinate + BlockWidth * 10);
                XCoordinate += BlockWidth;
            }

            return;
        }

        public void DrawDot (Graphics g)
        {
            g.setColor (Color.red);
            g.fillOval (DotXCoordinate, DotYCoordinate, DotWidth, DotWidth);

            return;
        }

        /* Generates a random number between 0 and 3 which is
           used to pick the direction for the next movement.
        */
        public void PickDirection ()
        {
            switch (Generator.nextInt(4))
            {
                case 0:
                    DotYCoordinate -= BlockWidth;
                    break;

                case 1:
                    DotXCoordinate += BlockWidth;
                    break;

                case 2:
                    DotYCoordinate += BlockWidth;
                    break;

                case 3:
                    DotXCoordinate -= BlockWidth;;
                    break;

                default:
            }

            return;
        }

        /* This method checks to see if the person has reached
           the edge of the town. It checks the coordinates of
           the dot against the coordinates of the grid.
        */
        public boolean CheckBorder ()
        {
            /* Default is false unless the check turns out to be true */
            boolean Result = false;

            if (DotXCoordinate < DefaultCoordinate ||
                DotXCoordinate + DotWidth > DefaultCoordinate + BlockWidth * 10 ||
                DotYCoordinate < DefaultCoordinate ||
                DotYCoordinate + DotWidth > DefaultCoordinate + BlockWidth * 10)
            {
                Result = true;
            }

            return Result;
        }

        public void actionPerformed(ActionEvent e)
        {
            /* Toggle the flag, if it has started
               stop it; otherwise, start it.
            */
                Graphics g=getGraphics();
            if (StartFlag)
            {
                StartFlag = !StartFlag;
                StepCounter = 0;
                Start.setLabel("Start");
                DotXCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;
                DotYCoordinate = DefaultCoordinate + 5 * BlockWidth - DotWidth / 2;
                repaint();
            }
            else
            {
                while (!CheckBorder() && StepCounter < 50)
                {
                    PickDirection();
                            try
                            {                        
                            g.setColor(Color.WHITE);
                            g.fillRect(0,0,500,500);
                            DrawGrid(g);
                            DrawDot(g);
                            Thread.sleep(1000);
                            
                            }
                            catch(Exception ex)
                            {
                            }

                    StepCounter++;
                }
                      repaint();

                StartFlag = !StartFlag;
                Start.setLabel("Reset");

            }

            return;
        }
    }
    0
     

    Author Comment

    by:UltimateApocalypse
    Thanks!! ^_^
    0
     
    LVL 14

    Expert Comment

    by:sudhakar_koundinya
    :-)
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Hire Top Freelancers to Complete Java Projects

    Source the talented Expert Exchange community
    for top quality work on your Java projects.

    Hire the best. Collaborate easily. Get quality work.

    INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
    Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
    This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
    This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

    913 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now