Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Why isn't this rectangle moving?

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question Why isn't this rectangle moving?

    Ok so I am trying to make a galaga game and I'm not getting very far at all. I just tried to make a rectangle be the spaceship and have you able to move it left and right, but it won't work. I added a keylistener and told it to add 5 to x when right arrowkey is hit and subtract 5 from x when the left arrow key is hit but the rectangle doesn't move when I run this program! Here is my code of what I did:

    package galaga;
     
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
     
    import javax.swing.JFrame;
     
    public class mainmethod extends JFrame{
    	int x = 200, y= 300;
    	KL bob = new KL();
    	public mainmethod() {
    		super("Galaga");
    		setVisible(true);
    		setLocation(150,150);
    		setSize(400,400);
    		addKeyListener(bob);
    	}
     
    	public class KL implements KeyListener{
     
     
    		public void keyPressed(KeyEvent e) {
    			if(e.getKeyCode() == KeyEvent.VK_LEFT) {
    			x = x-5;
    			}
    			if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
    			x = x+5;
    			}
    		}
    		public void keyReleased(KeyEvent e) {
     
     
    		}
     
    		@Override
    		public void keyTyped(KeyEvent e) {
     
     
    		}
    	}
    	public void paint(Graphics g) {
    		Image dbImage = createImage(getWidth(), getHeight());
    		Graphics dbGraphics = dbImage.getGraphics();
    		paintComponent(dbGraphics);
    		g.drawImage(dbImage, 0, 0, this);
    		}
     
    	public void paintComponent(Graphics g){
    		g.setColor(Color.CYAN);
    		Rectangle blarp = new Rectangle(x, y, 150, 150);
    		g.fillRect((int) blarp.getX(), (int) blarp.getY(), 90, 50);
     
    	}
     
     
     
     
     
     
     
     
     
     
    }

    Please help me and thanks if you take the time to read this


  2. #2
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Why isn't this rectangle moving?

    Quote Originally Posted by mkrage View Post
    Why isn't this rectangle moving?
    1. After changing x in the KeyListener routine you don't redraw(), so KeyListener has no effect on what you see.

    2. x and y are not used in the drawImage method, so no matter what you do with the value of x, nothing changes. (Hint: give initial values of x and y so that the rectangle is somewhere within the frame. Then use x,y in drawImage)



    Cheers!

    Z

  3. #3
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Why isn't this rectangle moving?

    Also you don't want to draw directly into a JFrame. Instead draw in the paintComponent override method of a JPanel or other class derived from JComponent. Be sure to call the super method first. Finally, your KeyListener won't work if the component listened to doesn't have the focus. For Swing applications it's usually better to use Key Bindings and not KeyListeners.

  4. #4
    Junior Member
    Join Date
    Oct 2012
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Why isn't this rectangle moving?

    Quote Originally Posted by Zaphod_b View Post
    1. After changing x in the KeyListener routine you don't redraw(), so KeyListener has no effect on what you see.

    2. x and y are not used in the drawImage method, so no matter what you do with the value of x, nothing changes. (Hint: give initial values of x and y so that the rectangle is somewhere within the frame. Then use x,y in drawImage)



    Cheers!

    Z
    Ok for number 1 do i put repaint() (redraw() didnt work) inside the keylistener or where do i put it?
    And for number 2 idk what u mean by initialize x. Does that just mean do x=150 in the paint or paintcomponent method. Sorry I do not understand your basic helpful message. I am still a beginner to programing and am not taking a class, i am just doing this on free time but thank you soooooooo much for trying to help!


    -mkrage

  5. #5
    Junior Member
    Join Date
    Oct 2012
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Why isn't this rectangle moving?

    Quote Originally Posted by curmudgeon View Post
    Also you don't want to draw directly into a JFrame. Instead draw in the paintComponent override method of a JPanel or other class derived from JComponent. Be sure to call the super method first. Finally, your KeyListener won't work if the component listened to doesn't have the focus. For Swing applications it's usually better to use Key Bindings and not KeyListeners.
    Ok first of all thank you for your help. Second its better if I draw on a JPanel an add it on and i am not familiar with key bindings and how they work! If you could tell a brief explanation on how they work and are set up and what parameter they take that would be much appreciated!

    Thanks for your help

    -mkrage

  6. #6
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: Why isn't this rectangle moving?

    Quote Originally Posted by mkrage View Post
    I am still a beginner to programing
    That's OK. No one was born knowing this stuff, you know.

    First of all, you should heed curmudgeon's advice. (His screen name is a misnomer. Don't be fooled; he's not curmudgeonly at all. Well, not usually.)

    Anyhow...

    What I wanted to do was to get you to the point were you could actually see results you expect with the program you started with. I mean, this stuff is fun only when "something" works, right? Look for tutorial material to see better examples of the usual way of writing Swing graphics applications.

    In the meanwhile, look at documentation for the methods that you use. For example drawImage.

    So...

    Quote Originally Posted by mkrage View Post
    ...idk what u mean by initialize x...
    That means give the instance fields x (and y) valid values in the mainmethod class.

    First of all, you have this in the paint method:
            g.drawImage(dbImage, 0, 0, this);
    That does not depend on x and y, so changing x won't move the image.

    For now, try changing it to
            g.drawImage(dbImage, x, y, this);

    Next you have this to initialize the variables x and y.
    public class mainmethod extends JFrame{
    	int x = 200, y= 300;

    But the way you have set the frame size, that's outside the frame (won't show up on the screen).
    For now, change the initialization to something like
        int x = 75, y= 75;

    Finally, at the end of the keyPressed method, you need to repaint, otherwise, the new value of x won't be immediately effective on what you are seeing.

    You can even instrument that method to make sure the arrow keys are changing the value of x:
            public void keyPressed(KeyEvent e) {
                System.out.println("Entering keypressed(): x = " + x);
                if(e.getKeyCode() == KeyEvent.VK_LEFT) {
                x = x - 5;
                }
                if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
                x = x + 5;
                }
                System.out.println("Repainting with x = " + x);
                repaint();
            }

    Anyhow once you see that it can be done, it's time to get on to the better way(s) of doing things that curmudgeon suggested.


    Cheers!

    Z
    Last edited by Zaphod_b; October 22nd, 2012 at 10:51 AM.

  7. #7
    Junior Member
    Join Date
    Oct 2012
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Why isn't this rectangle moving?

    Yes thank you so much! I now have a moving rectangle! I now understand what you have to do to initialize and how you must use repaint! Thank you so much!

Similar Threads

  1. How to Create a Word Rectangle
    By Pettsa in forum Object Oriented Programming
    Replies: 34
    Last Post: June 4th, 2012, 12:31 AM
  2. Better solution for moving my rectangle? (simple game)
    By JohnZ in forum Java Theory & Questions
    Replies: 5
    Last Post: May 24th, 2012, 09:54 AM
  3. Replies: 3
    Last Post: November 10th, 2011, 07:11 AM
  4. Rectangle questions
    By stacksofamber in forum Java Theory & Questions
    Replies: 3
    Last Post: September 5th, 2011, 12:43 PM
  5. Dropping to graphic element dragged from JList
    By tua1 in forum AWT / Java Swing
    Replies: 1
    Last Post: November 29th, 2008, 08:22 AM

Tags for this Thread