Results 1 to 7 of 7
  1. #1
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default Move things in Applet

    I am just trying to move a rectangle in a diagonal line. When the applet pops up, the rectangle is there but doesn't move. If i drag the sides of the applet to make it bigger or smaller the rectangle will redraw itself and move, but I want it to move without touching the window.

    Java Code:
    package javaapplication3;
    
    import java.applet.Applet;
    import java.awt.*;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.Random;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    /**
     *<applet code = "Images" width = 800 height = 50>
     * </applet>
     * 
     */
    public class Main extends Applet implements Runnable{
    
        int rectX = 10;
        int rectY = 10;
        Thread t;
        public void init() {
            t = new Thread();
            t.start();
        }
    
        public void paint(Graphics g) {
            g.setColor(Color.BLACK);
            g.fillRect(rectX, rectY, 10, 20);
            rectX++;
            rectY++;
        }
        public void run() {
            try {
                while(true) {
                    repaint();
                    t.sleep(100);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public void update(Graphics g) {
            paint(g);
        } 
    
    }
    Why does it only repaint when I resize the window?

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

    Default

    Please don't take this as criticism but rather as remarks to help you get on your way with coding. Here are some problems I found and suggestions:

    1) You're coding an Applet which uses the relatively outdated AWT library. Instead use Swing and create a JApplet or JFrame.

    2) You create a Thread, t, and call start on it, but you never give it a Runnable object when you construct it. This is the reason that nothing is happening, why your run method is not running.

    3) You need to call the super's paint method as the first method in your paint method (or if you use Swing and override a JPanel's paintComponent, then you must call super.paintComponent(g) as the first method of this override).

    4) You have program logic (rectX++ and rectY++) in your paint or paintComponent method. Don't do this as you don't have full control on when this will be called. Much better is to have the logic outside of this method, store the results in a class variable, and call repaint() which will then call the paint (or paintComponent) method indirectly.

    Myself, I'd use Swing, create a JPanel that has it's paintComponent method overridden, use a Swing Timer to and display it in either a JApplet or JFrame. something like,

    Java Code:
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    
    public class MovingRect extends JPanel {
    
      private static final int TIMER_DELAY = 15; // time between "ticks"
      private static final Dimension PANEL_SIZE = new Dimension(400, 200);
      private static final int RECT_WIDTH = 10;
      private static final int RECT_HEIGHT = 20;
      
      //initial and subsequent location of the rect
      private int rectX = 10;
      private int rectY = 10;
      
      //how far to move rect with each "tick"
      private int deltaX = 2; 
      private int deltaY = 2;
    
      public MovingRect() {
        setBackground(Color.white);
        setPreferredSize(PANEL_SIZE);
        new Timer(TIMER_DELAY, new ActionListener() {
          public void actionPerformed(ActionEvent arg0) {
            // check if rect has bounced off of left or right walls, then set deltaX
            if (rectX < 0) {
              deltaX = Math.abs(deltaX);
            } else if (rectX + RECT_WIDTH > MovingRect.this.getWidth()) {
              deltaX = -Math.abs(deltaX);
            }
            
            // check if rect has bounced off top or bottom walls, set deltaY
            if (rectY < 0) {
              deltaY = Math.abs(deltaY);
            } else if (rectY + RECT_HEIGHT > MovingRect.this.getHeight()) {
              deltaY = -Math.abs(deltaY);
            }        
            
            rectX += deltaX;
            rectY += deltaY;
            MovingRect.this.repaint();
          }
        }).start();
      }
      
      @Override
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.fillRect(rectX, rectY, RECT_WIDTH, RECT_HEIGHT);
      }
      
      private static void createAndShowGUI() {
        JFrame frame = new JFrame("MovingRect Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new MovingRect());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
    
      }
      
    
    }

    edit: The above code will run all by itself by creating a JFrame and placing the MovingRect JPanel into the JFrame's contentPane. To run this as an applet, just create a JApplet and place the MovingRect JPanel in the applet's contentPane:
    Java Code:
    import javax.swing.JApplet;
    import javax.swing.SwingUtilities;
    
    public class MovingRectApplet extends JApplet {
      @Override
      public void init() {
        try {
          SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
              getContentPane().add(new MovingRect());
            }
          });
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    Last edited by Fubarable; 07-25-2009 at 12:15 AM.

  3. #3
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    First...getting to 20 posts -_-

  4. #4
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Please don't take this as criticism but rather as remarks to help you get on your way with coding. Here are some problems I found and suggestions:

    1) You're coding an Applet which uses the relatively outdated AWT library. Instead use Swing and create a JApplet or JFrame.

    2) You create a Thread, t, and call start on it, but you never give it a Runnable object when you construct it. This is the reason that nothing is happening, why your run method is not running.

    3) You need to call the super's paint method as the first method in your paint method (or if you use Swing and override a JPanel's paintComponent, then you must call super.paintComponent(g) as the first method of this override).

    4) You have program logic (rectX++ and rectY++) in your paint or paintComponent method. Don't do this as you don't have full control on when this will be called. Much better is to have the logic outside of this method, store the results in a class variable, and call repaint() which will then call the paint (or paintComponent) method indirectly.

    Myself, I'd use Swing, create a JPanel that has it's paintComponent method overridden, use a Swing Timer to and display it in either a JApplet or JFrame. something like,

    Java Code:
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    
    public class MovingRect extends JPanel {
    
      private static final int TIMER_DELAY = 15; // time between "ticks"
      private static final Dimension PANEL_SIZE = new Dimension(400, 200);
      private static final int RECT_WIDTH = 10;
      private static final int RECT_HEIGHT = 20;
      
      //initial and subsequent location of the rect
      private int rectX = 10;
      private int rectY = 10;
      
      //how far to move rect with each "tick"
      private int deltaX = 2; 
      private int deltaY = 2;
    
      public MovingRect() {
        setBackground(Color.white);
        setPreferredSize(PANEL_SIZE);
        new Timer(TIMER_DELAY, new ActionListener() {
          public void actionPerformed(ActionEvent arg0) {
            // check if rect has bounced off of left or right walls, then set deltaX
            if (rectX < 0) {
              deltaX = Math.abs(deltaX);
            } else if (rectX + RECT_WIDTH > MovingRect.this.getWidth()) {
              deltaX = -Math.abs(deltaX);
            }
            
            // check if rect has bounced off top or bottom walls, set deltaY
            if (rectY < 0) {
              deltaY = Math.abs(deltaY);
            } else if (rectY + RECT_HEIGHT > MovingRect.this.getHeight()) {
              deltaY = -Math.abs(deltaY);
            }        
            
            rectX += deltaX;
            rectY += deltaY;
            MovingRect.this.repaint();
          }
        }).start();
      }
      
      @Override
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.fillRect(rectX, rectY, RECT_WIDTH, RECT_HEIGHT);
      }
      
      private static void createAndShowGUI() {
        JFrame frame = new JFrame("MovingRect Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new MovingRect());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
    
      }
      
    
    }

    edit: The above code will run all by itself by creating a JFrame and placing the MovingRect JPanel into the JFrame's contentPane. To run this as an applet, just create a JApplet and place the MovingRect JPanel in the applet's contentPane:
    Java Code:
    import javax.swing.JApplet;
    import javax.swing.SwingUtilities;
    
    public class MovingRectApplet extends JApplet {
      @Override
      public void init() {
        try {
          SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
              getContentPane().add(new MovingRect());
            }
          });
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    A couple questions about this...

    Java Code:
    public MovingRect() {
        setBackground(Color.white);
        setPreferredSize(PANEL_SIZE);
        new Timer(TIMER_DELAY, new ActionListener() {
    Where do these methods from? Are they inherited from JPanel? I am looking at the JPanel API and I don't see these methods listed. Are they from some other class that JPanel inherits? The Timer API says the Timer class is in -- extended by java.util.Timer
    So how are you able to use this? And the constructor is also different from the ones in Java 2 Platform SE 5.0

    Java Code:
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
    How does the class even know Runnable? And why is a Runnable necessary if you are not using threads?

  5. #5
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    And

    Java Code:
         rectX += deltaX;
            rectY += deltaY;
            MovingRect.this.repaint();
          }
        }).start();
    Why is start(); there?

  6. #6
    Mr.Beans's Avatar
    Mr.Beans is offline Senior Member
    Join Date
    Apr 2009
    Location
    Virginia Beach, Virginia
    Posts
    149
    Rep Power
    0

    Default

    Where do these methods from? Are they inherited from JPanel?
    JPanel inherits them from JCompnent.

    So how are you able to use this? And the constructor is also different from the ones in Java 2 Platform SE 5.0
    Namespace. There is more than one Timer class. They are just in different packages.
    Timer


    Why is start(); there?
    You just got lost in the code

    it's really just
    Java Code:
    new Timer(TIMER_DELAY, new ActionListener() { ....... }).start();
    the new ActionListener creates a class which implements the ActionListener interface in the method declarations given. The instance of that class is then passed into the Timer Constructor.


    Mr. Beans

  7. #7
    leeya is offline Member
    Join Date
    Feb 2014
    Posts
    1
    Rep Power
    0

    Default Re: Move things in Applet

    hey
    Question :
    line 30 in your code :
    MovingRect.this.getWidth()
    what does it mean?
    you call the class and then "this"
    can you explain?

Similar Threads

  1. Replies: 28
    Last Post: 09-15-2010, 10:21 AM
  2. how can i move from Frame to another
    By the swan in forum AWT / Swing
    Replies: 2
    Last Post: 04-04-2009, 04:24 PM
  3. How to move a ball across the applet window?
    By getkiran in forum Java Applets
    Replies: 3
    Last Post: 03-05-2009, 08:45 AM
  4. A good Java installation package can make things much easier
    By freezea in forum Reviews / Advertising
    Replies: 2
    Last Post: 02-01-2009, 12:03 PM
  5. May someone explain what these things means in Java
    By quickfingers in forum New To Java
    Replies: 2
    Last Post: 01-26-2008, 05:45 AM

Posting Permissions

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