Page 1 of 2 12 LastLast
Results 1 to 20 of 23
Like Tree1Likes

Thread: KeyListener?

  1. #1
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    317
    Rep Power
    2

    Default KeyListener?

    I want to make a program that will move a square to the left if you press "a", and to the right if you press "d". (Once I know how to do this I can figure out W and S for up and down by myself). What code would I use for doing that? Here is the program I have now. I used the oracle tutorial but it just shows how to handle for if ANY key is pressed.

    This is what I used How to Write a Key Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class myGame extends JComponent {
        public int x = 20;
        public int y = 20;
    
        myGame() {
            JFrame f = new JFrame("The most advanced game in the world");
            JPanel p = new JPanel();
            // New code
            p.setLayout(new BorderLayout());
            p.add(this);
            // End new code
            f.add(p);
            f.setSize(500, 500);
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            // Modified code
            g.drawString("Hello", 20, 20);
            g.fillRect(x, y, 50, 50);
            // End modified code
        }
    
        public static void main(String[] args) {
            new myGame();
        }
    }

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,618
    Rep Power
    5

    Default Re: KeyListener?

    Normally I use keylisteners just check for the desired key and then call the appropriate method. You could also use keybindings and map the specific key to the method you want to call. It's pretty well explained in the tutorials. Keybindings may also solve some potential focus issues. How to Use Key Bindings (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    pj6444 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    164
    Rep Power
    2

    Default Re: KeyListener?

    What you would need to do is have your class implement KeyListener and use the given methods.

    In this method you could do something like this.

    Java Code:
    public void keyPressed(KeyEvent e) {
        int k = e.getKeyCode();
        if(k == KeyEvent.VK_D) {
            // move right
        }
    }
    Also for this, you will need to addKeyListener(this) in the constructor and set the focus by using setFocusable(true) or requestFocus()

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,965
    Rep Power
    8

    Default Re: KeyListener?

    Shameless self-promotion: the link in my signature to Static Void Games contains tutorials on exactly this. :)
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    317
    Rep Power
    2

    Default Re: KeyListener?

    Great code. But how would I say for example: if the specific key w is pressed, move up one pixel? I know the code for the action to move up one pixel, but not for saying that if w is pressed, then do that.

  6. #6
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,965
    Rep Power
    8

    Default Re: KeyListener?

    You've received several replies explaining exactly what to do, or pointing you to places that contain the information you're looking for. What have you tried? We can't help you if you're just going to ignore our replies.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    pj6444 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    164
    Rep Power
    2

    Default Re: KeyListener?

    Quote Originally Posted by MW130 View Post
    Great code. But how would I say for example: if the specific key w is pressed, move up one pixel? I know the code for the action to move up one pixel, but not for saying that if w is pressed, then do that.
    This is exactly what I showed you before.


    What you would need to do is have your class implement KeyListener and use the given methods.

    In this method you could do something like this.

    Java Code:
    Java Code:
    public void keyPressed(KeyEvent e) {
        int k = e.getKeyCode();
        if(k == KeyEvent.VK_D) {
            // move right
        }
    }
    Also for this, you will need to addKeyListener(this) in the constructor and set the focus by using setFocusable(true) or requestFocus()

  8. #8
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    317
    Rep Power
    2

    Default Re: KeyListener?

    Quote Originally Posted by pj6444 View Post
    This is exactly what I showed you before.
    No, I know but where in that code does it specifically say that IF you press the left key, THEN it will move left? I only see it say do this if a key is pressed. I am not ignoring the answers.

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,618
    Rep Power
    5

    Default Re: KeyListener?

    That method is called regardless of what key you press. It is up to you to test which key is pressed and then invoke the appropriate method. You need to check the KeyEvent API to determine how to test for whatever key you want. The example provided tests for the character 'd'.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  10. #10
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    317
    Rep Power
    2

    Default Re: KeyListener?

    Quote Originally Posted by jim829 View Post
    That method is called regardless of what key you press. It is up to you to test which key is pressed and then invoke the appropriate method. You need to check the KeyEvent API to determine how to test for whatever key you want. The example provided tests for the character 'd'.

    Regards,
    Jim
    Oh, thanks for the reply! After looking over everything, it makes a lot more sense. Now I know how to do it for a specific key.

    The only thing is that I updated the code and when I DO press "d", nothing happens. I called the repaint method in the code, but it doesn't seem to matter :(
    Any help is appreciated.

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class myGame extends JComponent {
        public int x = 20;
        public int y = 20;
    
        myGame() {
            JFrame f = new JFrame("The most advanced game in the world");
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            p.add(this);
            f.add(p);
            f.setSize(500, 500);
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            // Modified code
            g.drawString("Hello", 20, 20);
            g.fillRect(x, y, 50, 50);
            // End modified code
        }
    
    public void keyPressed(KeyEvent e) {
        int k = e.getKeyCode();
        if(k == KeyEvent.VK_D) {
    x++;
    repaint();
        }
    }
        public static void main(String[] args) {
            new myGame();
        }
    }

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,618
    Rep Power
    5

    Default Re: KeyListener?

    You need to implement the keyListener interface either directly via the myGame glass or thru another class. Then you need to add an instance of the keyListener to the component on which you are listening for events. If you have not worked with listeners before you need to check out the tutorials in my signature and see how to write a keylistener.

    Regards,
    Jim
    MW130 likes this.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  12. #12
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    317
    Rep Power
    2

    Default Re: KeyListener?

    Ok I will check it out. Last question: I added the interface by implementing it in myGame, but since keylistener is an interface, I cannot directly make an instance of it and then add it to the JPanel.. so how would I add it?

  13. #13
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,618
    Rep Power
    5

    Default Re: KeyListener?

    There are lots of ways. If your myGame class doesn''t implement the interface you can just use the new operator with an interface because it creates an anonymous class.

    e.g.
    Java Code:
    KeyListener kl = new KeyListener() {
       methods here
    };
    The downside of that is you have to implement all the methods (or at least have dummy ones for what you don't care about).

    Better is to do this

    Java Code:
    KeyAdapter ka = new KeyAdapter() {
        // method here
    };
    Adapter methods are for interfaces with more than one method to declare. The adapter class is just a class with empty methods. You override what you want and fill in the guts.

    Best is use an inner class.

    Java Code:
    private class MyListener extends KeyAdapter {
      // methods here
    }
    Then later, you just add an instance of the class via the addListener method of the target component. I prefer inner classes because they have access to all
    the enclosing classes variables and they are clean. The better vs best is based on my own preferences.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  14. #14
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    317
    Rep Power
    2

    Default Re: KeyListener?

    Quote Originally Posted by jim829 View Post
    There are lots of ways. If your myGame class doesn''t implement the interface you can just use the new operator with an interface because it creates an anonymous class.

    e.g.
    Java Code:
    KeyListener kl = new KeyListener() {
       methods here
    };
    The downside of that is you have to implement all the methods (or at least have dummy ones for what you don't care about).

    Better is to do this

    Java Code:
    KeyAdapter ka = new KeyAdapter() {
        // method here
    };
    Adapter methods are for interfaces with more than one method to declare. The adapter class is just a class with empty methods. You override what you want and fill in the guts.

    Best is use an inner class.

    Java Code:
    private class MyListener extends KeyAdapter {
      // methods here
    }
    Then later, you just add an instance of the class via the addListener method of the target component. I prefer inner classes because they have access to all
    the enclosing classes variables and they are clean. The better vs best is based on my own preferences.

    Regards,
    Jim
    Ugh I know you will probably tell me to go read more and I feel like an idiot asking this but
    when you do
    Java Code:
        KeyListener kl = new KeyListener() {}
    why the heck are there brackets there? I thought that would just instantiate the object.. I have never seen brackets after making an object before.. Anyway, if I post the code here, could you show me on my code what to change? I find that that is the best way I understand, seeing the before & after. Thanks for all your help, it is so nice of you.

  15. #15
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    317
    Rep Power
    2

    Default Re: KeyListener?

    I did the first option you said, and it is still not moving when pressing d. The code is:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class myGame extends JComponent {
        public int x = 20;
        public int y = 20;
    
        KeyListener kl = new KeyListener() {
    
    		@Override
    		public void keyTyped(KeyEvent e) {
    			// TODO Auto-generated method stub
    			
    		}
    
    		@Override
    		public void keyPressed(KeyEvent e) {
    			// TODO Auto-generated method stub
    			
    		}
    
    		@Override
    		public void keyReleased(KeyEvent e) {
    			// TODO Auto-generated method stub
    			
    		}
        	};
        myGame() {
            JFrame f = new JFrame("The most advanced game in the world");
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            p.add(this);
            f.add(p);
            f.setSize(500, 500);
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		Component k1 = null;
    		f.add(k1);
    
        }
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawString("Hello", 20, 20);
            g.fillRect(x, y, 50, 50);
        }
    
    public void keyPressed(KeyEvent e) {
        int k = e.getKeyCode();
        if(k == KeyEvent.VK_D) {
    x=x+20;
    repaint();
        }
    }
        public static void main(String[] args) {
            new myGame();
        }
    
    }

  16. #16
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,618
    Rep Power
    5

    Default Re: KeyListener?

    You're misunderstanding. You need to move your keyPressed code from below (get rid of that method) and put it in the same method above in the anonymous class. Then add an instance of the anonymous class to your component via addKeyListener(). And check out the tutorials. They give good explanations.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  17. #17
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    317
    Rep Power
    2

    Default Re: KeyListener?

    Ok, the method switch is done. How do i add the instance of the anonymous class, and to which component do I add it to?
    I tried
    Java Code:
    f.addKeyListener(k1);
    and got an error.

    Also, when you write the KeyListener kl = new KeyListener() {}
    why the heck are there brackets there? I thought that would just instantiate the object.. I have never seen brackets after making an object before.. Anyway, if I post the code here, could you show me on my code what to change? I find that that is the best way I understand, seeing the before & after.

    Thanks for all your help

    EDIT: I JUST ADDED IT AND THE PROGRAM IS AMAZING OMG THANK YOU SO MUCH JIM YOU ARE AWESOME (if you can answer the above question though that would be awesome :)
    )

  18. #18
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    317
    Rep Power
    2

    Default Re: KeyListener?

    Jim I am so happy right now if I ever make something good I will literally mention jim829 for getting me into Java and explaining everything so well (EXCEPT FOR THE "KeyListener kl = new KeyListener() {} BRACKETS? part) jk that is fine. Thanks again Jim

  19. #19
    MW130 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    317
    Rep Power
    2

    Default Re: KeyListener?

    But why does the KeyListener kl = new KeyListener(){}; need those three methods? Is it an interface?

  20. #20
    zFollette is offline ▼ dafuq did I do?
    Join Date
    Dec 2013
    Posts
    203
    Rep Power
    0

    Default Re: KeyListener?

    Quote Originally Posted by MW130 View Post
    But why does the KeyListener kl = new KeyListener(){}; need those three methods? Is it an interface?
    I just picked up on this thread now, I have no idea what is going on so Ill take my best whack at it. You may be trying to call a new instance of a class you have made. In this case, you are calling a new instance of the Java Keylistener, which does require 3 methods. So check your imports and class names and you should figure out your problem.

Page 1 of 2 12 LastLast

Similar Threads

  1. Keylistener
    By dyelax in forum New To Java
    Replies: 4
    Last Post: 09-20-2012, 07:06 PM
  2. Need help with KeyListener
    By McDucky in forum New To Java
    Replies: 3
    Last Post: 09-16-2012, 05:35 PM
  3. Help with KeyListener
    By armyson in forum New To Java
    Replies: 1
    Last Post: 11-25-2011, 12:56 PM
  4. Help with keylistener?
    By Kaizo in forum New To Java
    Replies: 4
    Last Post: 12-11-2010, 12:55 AM
  5. keyListener not doing anything
    By imorio in forum AWT / Swing
    Replies: 10
    Last Post: 08-17-2010, 10:46 PM

Posting Permissions

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