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 5 of 5

Thread: Making an image move with arrow keys

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

    Default Making an image move with arrow keys

    I need help with making an image of a spaceship move when I press an arrow key. For now, all I want to do is make the spaceship image move to the right when I press the right arrow key. Here's part of my code that I think could be the problem:

    	public void paintComponent(Graphics g){
    		super.paint(g);
    		g.drawImage(starfield,0,5,null);
    		g.drawImage(spaceship,shipx,shipy,null);
     
    	}
     
    	public class Keyboard implements KeyListener{
    		public void keyTyped(KeyEvent event){}
    		public void keyPressed(KeyEvent event){
    			if(event.getKeyCode()==KeyEvent.VK_RIGHT){
    				shipx++;
    				repaint();
    			}
    		}
    		public void keyReleased(KeyEvent event){}
    	}

    When I compile the above code in JCreator, there are no errors. It's just that the image of the spaceship doesn't move at all. I found many of examples online, but they were too complicated for me to follow. All help is greatly appreciated.
    Last edited by Clex19; July 5th, 2012 at 09:32 PM. Reason: Trimmed down my code to make it easier to follow


  2. #2
    Member
    Join Date
    Jul 2012
    Posts
    83
    My Mood
    Cynical
    Thanks
    3
    Thanked 9 Times in 9 Posts

    Default Re: Making an image move with arrow keys

    One issue: you show a KeyListener class, but you don't show code where you've added a KeyListener to a component, and that is absolutely necessary for KeyListeners to work. KeyListeners are also very persnickety in that they refuse to work if the component being listened to has the focus, and in fact if you read the Swing tutorials on them, you'll see that the creators of Swing recommend that you not use them in Swing applications but instead use Key Bindings for most situations, and in fact in this particular case, Key Bindings work great.

    For example:

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
     
    import javax.swing.*;
     
    @SuppressWarnings("serial")
    public class MoveBall extends JPanel {
       private static final String UP = "UP";
       private static final String DOWN = "DOWN";
       private static final String LEFT = "LEFT";
       private static final String RIGHT = "RIGHT";
       private static final Color BACKGROUND = Color.black;
       private static final Color BALL_COLOR = Color.yellow;
       private static final int BALL_WIDTH = 30;
       private static final int PREF_WIDTH = 500;
       private static final int PREF_HEIGHT = PREF_WIDTH;
       private static final Dimension PREF_SIZE = new Dimension(PREF_WIDTH, PREF_HEIGHT);
       private int x = PREF_WIDTH / 2;
       private int y = PREF_HEIGHT / 2;
     
       public MoveBall() {
          setBackground(BACKGROUND);
     
          int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
          InputMap inputMap = getInputMap(condition);
          ActionMap actionMap = getActionMap();
     
          inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), UP);
          actionMap.put(UP, new AbstractAction() {
             public void actionPerformed(ActionEvent arg0) {
                y--;
                repaint();
             }
          });
     
          inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), DOWN);
          actionMap.put(DOWN, new AbstractAction() {
             public void actionPerformed(ActionEvent arg0) {
                y++;
                repaint();
             }
          });
     
          // etc for left and right
     
       }
     
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setColor(BALL_COLOR);
          g2.fillOval(x - BALL_WIDTH / 2, y - BALL_WIDTH / 2, 
                BALL_WIDTH, BALL_WIDTH);
       }
     
       @Override
       public Dimension getPreferredSize() {
          return PREF_SIZE;
       }
     
       private static void createAndShowGui() {
          JFrame frame = new JFrame("Move Ball");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new MoveBall());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
     
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    Last edited by Fubarable; July 5th, 2012 at 09:41 PM.

  3. The Following User Says Thank You to Fubarable For This Useful Post:

    Clex19 (July 5th, 2012)

  4. #3
    Junior Member
    Join Date
    Jul 2012
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Making an image move with arrow keys

    Thanks for the reply, Fubarable.

    Key binding looks very complicated to me, but I guess if there's no other way then I'll try my best to figure out how to do it that way. I thought it would be much easier, like mouse events.

  5. #4
    Member
    Join Date
    Jul 2012
    Posts
    83
    My Mood
    Cynical
    Thanks
    3
    Thanked 9 Times in 9 Posts

    Default Re: Making an image move with arrow keys

    Quote Originally Posted by Clex19 View Post
    Thanks for the reply, Fubarable.
    You're welcome.

    Key binding looks very complicated to me, but I guess if there's no other way then I'll try my best to figure out how to do it that way. I thought it would be much easier, like mouse events.
    For me, all of programming is complicated until I get familiar with it, and it's probably the same for you. I suggest that you read the key bindings tutorial, then try key bindings out, play with your code to see what different variations do. Then if you get stuck, come on back with your code attempt, and let's see if we can help you out.

    Oh, I also suggest that you not try to put key bindings into your big application just yet, but instead work with them in small toy programs like the one I posted. Don't add them to the large program until you've got them working in the small one and until you've ironed out all the kinks.

    Good luck!

  6. #5
    Junior Member
    Join Date
    Jul 2012
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Making an image move with arrow keys

    I managed to make it work with key binding. However, I also discovered how to do it the way I originally wanted:

    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
     
    public class AsteroidRun extends JFrame{
        static Image dbImage;
        static Graphics dbg;
        Image starfield;
        Image spaceship;
        private int shipx = 100;
        private int shipy = 200;
     
     
        public class AL extends KeyAdapter{
    		public void keyPressed(KeyEvent e){
    			int keyCode = e.getKeyCode();
    			if(keyCode == e.VK_LEFT){
    				shipx-=4;
    				repaint();
    			}
    			if(keyCode == e.VK_RIGHT){
    				shipx+=4;
    				repaint();
    			}
    			if(keyCode == e.VK_UP){
    				shipy-=4;
    				repaint();
    			}
    			if(keyCode == e.VK_DOWN){
    				shipy+=4;
    				repaint();
    			}
    		}
        }
     
        public AsteroidRun() {
        	starfield = new ImageIcon(AsteroidRun.class.getResource("Pics/starfield.jpg")).getImage();
    	spaceship = new ImageIcon(AsteroidRun.class.getResource("Pics/spaceship.png")).getImage();
     
        	addKeyListener(new AL());
        	setTitle("Asteroid Run");
        	setSize(500,400);
        	setResizable(false);
        	setLocationRelativeTo(null);
        	setVisible(true);
        	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
     
        public void paint(Graphics g){
    		dbImage = createImage(getWidth(),getHeight());
    		dbg = dbImage.getGraphics();
    		paintComponent(dbg);
    		g.drawImage(dbImage,0,0,this);
    	}
     
        public void paintComponent(Graphics g){
        	g.drawImage(starfield,0,0,this);
    	g.drawImage(spaceship,shipx,shipy,this);
        }
     
        public static void main(String[] args){
        	new AsteroidRun();
        }
     
    }

    Both ways work, but I prefer the above way. Nevertheless, figuring out key binding was a good learning experience!

Similar Threads

  1. Moving an image around the screen using the arrow keys.
    By nemo in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 19th, 2013, 12:08 AM
  2. Making a method to move blocks in a grid
    By geforce in forum What's Wrong With My Code?
    Replies: 60
    Last Post: May 22nd, 2012, 07:00 AM
  3. [SOLVED] Arrow keys to navigate a maze in a console program
    By B25Mitch in forum What's Wrong With My Code?
    Replies: 9
    Last Post: January 31st, 2012, 04:58 PM
  4. Need help making an image move from one side of screen to the other.
    By Xillius200 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 25th, 2011, 12:46 PM
  5. How to move an image (or how to delete one)
    By User in forum AWT / Java Swing
    Replies: 3
    Last Post: December 17th, 2009, 11:25 AM