Results 1 to 18 of 18
Like Tree1Likes
  • 1 Post By doWhile

Thread: Key Listeners

  1. #1
    wired-in=p is offline Member
    Join Date
    Jul 2011
    Posts
    38
    Rep Power
    0

    Default Key Listeners

    I have been trying to design a simple key listener that listens to the enter key. here is my code;
    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    
    public class pacman extends JFrame{
    	public pacman()
    	{
    		super();
    		setSize(500, 500);
    		mypanel second = new mypanel();
    		second.setFocusable(true);
    		add(second);
    		setVisible(true);
    		setDefaultCloseOperation(3);
    		validate();
    	}
    	public static void main(String args[])
    	{
    		pacman pac = new pacman();
    		
    	}
    	public class mypanel extends JPanel
    	{
    		public int x;
    		public int y;
    		public mypanel()
    		{
    			super();
    			 addKeyListener(new KeyAdapter(){
    				public void pressedkey(KeyEvent e)
    				{
    					System.out.println("Here");
    					if (e.getKeyCode()==KeyEvent.VK_UP)
    					{
    						y++;
    					}
    					else if (e.getKeyCode()==KeyEvent.VK_DOWN)
    					{	
    						y--;
    					}
    					else if (e.getKeyCode()==KeyEvent.VK_RIGHT)
    					{
    						x++;
    					}
    					else if (e.getKeyCode()==KeyEvent.VK_LEFT)
    					{
    						x--;
    					}
    					repaint();
    				}
    			});
    		}
    		public void paintComponent(Graphics g)
    		{
    			super.paintComponent(g);
    			g.setColor(Color.yellow);
    			x = this.getSize().width/2-15;
    			y = this.getSize().height/2-15;
    			g.fillOval(x, y, 30, 30);
    			g.setColor(Color.black);
    			this.setOpaque(true);
    			this.setBackground(Color.black);	
    		}
    	}
    }
    I cannot understand why it will not work
    I don't know whether i need to learn about key binding and setting the focus of the component

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

    Default Re: Key Listeners

    What API is pressedkey from? You can't make stuff up and expect it to work.

    And yes, you should look into learning how to use key bindings.

    Also: don't hard-code your x and y in the paintComponent method. What good will changing their values in your program if it's only going to be reset back to hard coded values whenever the component is painted?

    Also: don't set background or opaque from within paintComponent. These should be set once in the constructor.
    Last edited by Fubarable; 09-17-2011 at 12:27 AM.

  3. #3
    wired-in=p is offline Member
    Join Date
    Jul 2011
    Posts
    38
    Rep Power
    0

    Default Re: Key Listeners

    what did i make up? and what do i need to add to make it work

  4. #4
    wired-in=p is offline Member
    Join Date
    Jul 2011
    Posts
    38
    Rep Power
    0

    Default Re: Key Listeners

    I still don't understand why the program won't run even after i set the focus to my panel.

  5. #5
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: Key Listeners

    Quote Originally Posted by wired-in=p View Post
    what did i make up? and what do i need to add to make it work
    Read the API for KeyListener: pressedkey != keyPressed. For future reference, using the @Override annotation would have given you a compile time error and caught this error much earlier. And yes, look into using KeyBindings. Lastly, I recommend you take some time to read about java code conventions
    Fubarable likes this.

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

    Default Re: Key Listeners

    Exactly, pressedkey doesn't exist. It may sound right, but since it was made up, it overrides no super method and the JVM won't respond to it as it would to a proper method override. To use these things you must use the references available including the API and the tutorials. That's what they're for.

  7. #7
    wired-in=p is offline Member
    Join Date
    Jul 2011
    Posts
    38
    Rep Power
    0

    Default Re: Key Listeners

    isn't pressed key a method in the interface KeyListener?

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

    Default Re: Key Listeners

    Quote Originally Posted by wired-in=p View Post
    isn't pressed key a method in the interface KeyListener?
    Again, please read the API; don't guess! It's online -- do you need the link?

  9. #9
    wired-in=p is offline Member
    Join Date
    Jul 2011
    Posts
    38
    Rep Power
    0

    Default Re: Key Listeners

    now the key pressed method works but the if e.getKeyCode == VK_UP or for any other arrow key won't work

  10. #10
    mine0926 is offline Senior Member
    Join Date
    Apr 2010
    Location
    Philippines
    Posts
    580
    Rep Power
    5

  11. #11
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default Re: Key Listeners

    > or for any other arrow key won't work

    Define won't work. What do you expect to happen?

  12. #12
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,658
    Blog Entries
    7
    Rep Power
    21

    Default Re: Key Listeners

    Quote Originally Posted by camickr View Post
    Define won't work. What do you expect to happen?
    Miracles; why ask? ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  13. #13
    wired-in=p is offline Member
    Join Date
    Jul 2011
    Posts
    38
    Rep Power
    0

    Default Re: Key Listeners

    I read the key binding tutorial and it makes sense to me except for one thing.
    component.getInputMap().put(KeyStroke.getKeyStroke ("SPACE"),
    "pressed");
    component.getInputMap().put(KeyStroke.getKeyStroke ("released SPACE"),
    "released");
    component.getActionMap().put("pressed",
    pressedAction);
    component.getActionMap().put("released",
    releasedAction);
    //where pressedAction and releasedAction are javax.swing.Action objects
    I don't understand how to attach the "SPACE" string to the actual space key. I wouldn't know how to replace the space keystroke with any of the arrow keys in the code. Lastly, I don't know how to have the actions performed when a key is pressed or when its released.
    Last edited by wired-in=p; 09-17-2011 at 04:06 PM.

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

    Default Re: Key Listeners

    There are several ways of getting the KeyStroke for key binding. Myself, I like to use KeyStroke.getKeyStroke(int, int), the first int is obtained by using the vk_ constants held by the KeyEvent class. For instance, assuming your code has a String constant for up:

    Java Code:
       private static final String UP = "UP";

    Then you could do one key binding like so:
    Java Code:
          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();
             }
          });

    For example:
    Java Code:
    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();
             }
          });
       }
    }
    Edit: to get released vs pressed, look at the KeyStroke API for the appropriate method. Myself I'd use the getKeyStroke(int, int, boolean) for this.
    Last edited by Fubarable; 09-17-2011 at 04:19 PM.

  15. #15
    wired-in=p is offline Member
    Join Date
    Jul 2011
    Posts
    38
    Rep Power
    0

    Default Re: Key Listeners

    Thank you very much. One question, what is the 0 argument in KeyStroke.getKeyStroke for?

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

    Default Re: Key Listeners

    Quote Originally Posted by wired-in=p View Post
    Thank you very much. One question, what is the 0 argument in KeyStroke.getKeyStroke for?
    A good habit to get in to is to first check the API: KeyStroke API

  17. #17
    wired-in=p is offline Member
    Join Date
    Jul 2011
    Posts
    38
    Rep Power
    0

    Default Re: Key Listeners

    Thanks again, my program now works. however, i made the ball move one pixel when i press an arrow key. it was moving too slow so i changed it to 10 pixels, which is a better speed but it seems like it is jumping around. is there anyway i can lower the time it takes to press a key so the ball moves smoother?

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

    Default Re: Key Listeners

    Consider using a Timer for your game loop. You could have a right-arrow key-down change a moveRight boolean to true and key-up change it to false and the game loop would move the sprite to the right if (moveRight).

Similar Threads

  1. two different Listeners
    By Billaguana in forum New To Java
    Replies: 8
    Last Post: 01-21-2011, 03:20 AM
  2. key listeners
    By zjames in forum New To Java
    Replies: 22
    Last Post: 11-24-2010, 05:58 AM
  3. Can't implement listeners
    By xael in forum New To Java
    Replies: 3
    Last Post: 09-02-2010, 06:33 PM
  4. Help with Listeners
    By Psyclone in forum AWT / Swing
    Replies: 8
    Last Post: 02-09-2010, 07:21 PM
  5. Seriously need help on my listeners!!
    By themburu in forum Java Applets
    Replies: 4
    Last Post: 05-26-2008, 10:41 AM

Tags for this Thread

Posting Permissions

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