Results 1 to 8 of 8
  1. #1
    frenbel is offline Member
    Join Date
    Dec 2008
    Posts
    4
    Rep Power
    0

    Default Hey I'm new here and I have a big problem!

    I wrote a simple program that shows an image on an Applet screen, and by clicking the right arrow button on the keyboard it moves the image slowly to the right. The problem is, the program waits the whole time and then suddenly repaints the image to the right, instead of slowly dragging it..
    Just take a look at the code:

    import java.util.*;
    import java.awt.*;
    import java.applet.*;

    public class A extends Applet
    {
    public int x;
    public int y;
    public Image image;

    public void init()
    {
    x = 300;
    y = 300;
    setBackground(Color.white);
    resize(600,600);
    image = getImage(getDocumentBase(), "IMAGE001.JPG");
    }

    public void paint(Graphics g)
    {
    g.drawImage(image, x, y, this);
    }

    public boolean keyDown(Event e, int key)
    {
    if(key == e.RIGHT){
    for(int i = 0; i <= 20; i++)
    {
    x++;
    repaint();
    try
    {
    Thread.sleep(100);
    }
    catch (InterruptedException e1)
    {
    e1.printStackTrace();
    }
    }
    }

    return true;
    }
    }


    I really need help with this!
    Thanks in advance !!!

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    calling Thread.sleep(...) on the event thread will only put the whole GUI app to sleep (as you're finding out). Try doing this in a background thread.

    Better still, create a JApplet, do this in Swing and use a Swing Timer

    For instance (not 100% sure if this is fully kosher as I'm not well versed in AWT)
    Java Code:
      public boolean keyDown(Event e, int key)
      {
        if (key == Event.RIGHT)
        {
          new Thread(new Runnable()
          {
            public void run()
            {
              for (int i = 0; i <= 20; i++)
              {
                x++;
                System.out.println(x);
                repaint();
                try
                {
                  Thread.sleep(100);
                }
                catch (InterruptedException e1)
                {
                  e1.printStackTrace();
                }
              }
            }
          }).start();
        }
    
        return true;
      }

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    If you post back, I'll show you how to do this with a JApplet and a Swing timer.

  4. #4
    frenbel is offline Member
    Join Date
    Dec 2008
    Posts
    4
    Rep Power
    0

    Default

    Yeah I've never used JApplet and swing timer, it'll be great if you could show me how to use them.

    Thanks btw :).

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You're welcome. Please feel free to ask questions if you have any:

    Java Code:
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import java.net.URL;
    import java.util.Random;
    
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    import javax.swing.Timer;
    
    /**
     * creates a JPanel, mainPanel that shows the animation.
     * The mainPanel can be obtained via getComponent() method
     * @author Pete
     */
    public class MyAnimationPanel
    {
      private static final Dimension MAIN_SIZE = new Dimension(600, 600);
      private static final String DUKE_WEB_IMAGE = // Duke, he's my hero
        "https://duke.dev.java.net/images/thumbsup/thumbsup.gif";
      //private static final String IMAGE_PATH = "duke.gif";
      private static final int TIMER_DELAY = 10;
      private static final int MAX_Y = 6;
      private static final int MAX_X = 6;
      private JPanel mainPanel = new JPanel() // the main panel (of course)
      {
        private static final long serialVersionUID = 1L;
    
        @Override // do our drawing in here
        protected void paintComponent(Graphics g)
        {
          super.paintComponent(g);
          myPaint(g); // actually it will be done in this method.
        }
      };
      private Image image;
      private Point point = new Point(); //location of image
      private Random random = new Random(); // randomly moves image around
      // deltaP is the delta vector that I add to point with each iteration
      private Point deltaP = new Point(random.nextInt(MAX_X), random.nextInt(MAX_Y));  
      private Dimension imageSize;
    
      public MyAnimationPanel()
      {
        mainPanel.setPreferredSize(MAIN_SIZE);
        try
        {
          //image = ImageIO.read(getClass().getResourceAsStream(IMAGE_PATH));
          image = ImageIO.read(new URL(DUKE_WEB_IMAGE));
          imageSize = new Dimension(image.getWidth(mainPanel), image.getHeight(mainPanel));
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
        // initialize and start the animation Timer
        new Timer(TIMER_DELAY, new TimerListener()).start();
      }
    
      private void myPaint(Graphics g)
      {
        if (image != null)
        {
          g.drawImage(image, point.x, point.y, mainPanel);
        }
      }
    
      /**
       * @return JComponent, our mainPanel JPanel
       */
      public JComponent getComponent()
      {
        return mainPanel;
      }
      
      /**
       * ActionListener used by timer to perform animation 
       * @author Pete
       */
      private class TimerListener implements ActionListener
      {
        public void actionPerformed(ActionEvent e)
        {
          int x = 0;
          int y = 0;
          Dimension size = mainPanel.getSize();
          
          // if at a boundary of the mainPanel, change the direction and speed of sprite
          if (point.x <= 0)
          {
            x = random.nextInt(MAX_X);
            y = random.nextInt(MAX_Y);
            y = (random.nextBoolean()? y : -y);
            deltaP = new Point(x, y);
          }
          else if (point.x >= (size.width - imageSize.width))
          {
            x = -random.nextInt(MAX_X);
            y = random.nextInt(MAX_Y);
            y = (random.nextBoolean()? y : -y);
            deltaP = new Point(x, y);
          }
          
          if (point.y <= 0)
          {
            x = random.nextInt(MAX_X);
            x = (random.nextBoolean()? x : -x);
            y = random.nextInt(MAX_Y);
            deltaP = new Point(x, y);
          }
          else if (point.y > (size.height - imageSize.height))
          {
            x = random.nextInt(MAX_X);
            x = (random.nextBoolean()? x : -x);
            y = -random.nextInt(MAX_Y);
            deltaP = new Point(x, y);
          }
          // add point and deltaP vectors to move sprite
          point = new Point(point.x + deltaP.x, point.y + deltaP.y);
          mainPanel.repaint();
        }
      }
    
    }
    Java Code:
    import javax.swing.JApplet;
    
    /**
     * create a JApplet and add animation panel to the 
     * applet's contentPane 
     * @author Pete
     */
    public class MyA_Applet extends JApplet
    {
      public void init()
      {
        try
        { // create my class and display in a thread-safe way
          javax.swing.SwingUtilities.invokeAndWait(new Runnable()
          {
            public void run()
            {
              createGUI();
            }
          });
        }
        catch (Exception e)
        {
          System.err.println("createGUI didn't successfully complete");
        }
      }
    
      private void createGUI()
      {
        // create animation panel and add the mainPanel to the applet's content pane
        getContentPane().add(new MyAnimationPanel().getComponent());
      }
    }

  6. #6
    frenbel is offline Member
    Join Date
    Dec 2008
    Posts
    4
    Rep Power
    0

    Default

    Uh :confused: ... Thanks a lot but I really can't understand a thing, It's really complicated for me (I'm new to Graphics). I think I'm gonna have to study a lot more before asking about such complicated stuff.
    If you have any good tutorials for graphics, please send me!
    :)

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    If you haven't explored the Sun Java Tutorials site, you're in for a treat. There you'll find Swing tutorials, Graphics tutorials, Applet tutorials and a whole lot more. You can find it here:
    The Java™ Tutorials
    The best place to go is to click on the "Really Big Index" button.

    Good luck and HTH.

  8. #8
    frenbel is offline Member
    Join Date
    Dec 2008
    Posts
    4
    Rep Power
    0

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •