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

    Default Another way to add a keylistener to a JComponent?

    Hey guys, I wrote this program (with the help of Jim829) that makes a little square move around with the wasd keys. A huge problem that I had while creating it is adding the keylistener to my JFrame. In the end, I ended up creating an anonymous KeyListener class and adding that anonymous class to the JFrame. However, this anonymous class requires two other methods that I don't use, so I figured that there should be an easier way to do this. Does anyone know any other thing I could have done to add these keylisteners to the JFrame without creating an anonymous class? I had to create 4...
    Here is the code:
    Thanks for any and all help!

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Color;
    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 kw = new KeyListener(){
    
    		@Override
    		public void keyTyped(KeyEvent e) {
    			// TODO Auto-generated method stub
    			
    		}
    
    		@Override
    		public void keyPressed(KeyEvent e) {
            int k = e.getKeyCode();
            if (k == KeyEvent.VK_W){
            y=y-10;
            repaint();
    }
    		}
    
    		@Override
    		public void keyReleased(KeyEvent e) {
    			// TODO Auto-generated method stub
    			
    		}
        	
        
        };
        KeyListener ks = new KeyListener(){
    
    		@Override
    		public void keyTyped(KeyEvent e) {
    			// TODO Auto-generated method stub
    			
    		}
    
    		@Override
    		public void keyPressed(KeyEvent e) {
    int k = e.getKeyCode();
    if (k == KeyEvent.VK_S){
    	y = y+10;
    	repaint();
    }
    		}
    
    		@Override
    		public void keyReleased(KeyEvent e) {
    			// TODO Auto-generated method stub
    			
    		}
        	
        };
        KeyListener ka = new KeyListener(){
    
    		@Override
    		public void keyTyped(KeyEvent e) {
    			// TODO Auto-generated method stub
    			
    		}
    
    		@Override
    		public void keyPressed(KeyEvent e) {
            int k = e.getKeyCode();
            if(k == KeyEvent.VK_A){
    	    x=x-10;
    	    repaint();
    }
    		}
    
    		@Override
    		public void keyReleased(KeyEvent e) {
    			// TODO Auto-generated method stub
    			
    		}
        	
        };
        KeyListener kl = new KeyListener() {
     
            @Override
            public void keyTyped(KeyEvent e) {
                // TODO Auto-generated method stub
                 
            }
     
            @Override
            public void keyPressed(KeyEvent e) {
                int k = e.getKeyCode();
                if(k == KeyEvent.VK_D) {
            x=x+10;
            repaint();
                }
            }
     
            @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);
            f.addKeyListener(kl);
            f.addKeyListener(ka);
            f.addKeyListener(kw);
            f.addKeyListener(ks);
            p.setBackground(Color.blue);
            
        }
     
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.white);
            g.drawString("My First Game", 20, 20);
            g.fillRect(x, y, 50, 50);
        }
     
    
        public static void main(String[] args) {
            new myGame();
        }
     
    }

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

    Default Re: Another way to add a keylistener to a JComponent?

    Why are you creating four keylisteners? You only need one. And as I said in the other post, you can also use KeyAdapter to avoid implementing those methods. I would use a private inner class. So your code above would be:

    Java Code:
    private class MyKeyListener extends KeyAdapter {
       public void keyPressed(KeyEvent ke) {
          switch (ke.getKeyCode()) {
             case KeyEvent.VK_A:
                // do something
                break;
             case KeyEvent.VK_D:
                //do something
                break;
             case KeyEvent.VK_W:
                //do something
                break;
             case KeyEvent.VK_S:
                //do something
                break;
              default:
          }
          // rest of code common to all key events
       }
    }
    Then just use a single instance of it.

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

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

    Default Re: Another way to add a keylistener to a JComponent?

    Do all people that use KeyEvents use anonymous classes to add the event to the JComponent?

  4. #4
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,417
    Rep Power
    5

    Default Re: Another way to add a keylistener to a JComponent?

    Quote Originally Posted by MW130 View Post
    Do all people ...?
    I have no idea.

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

  5. #5
    pj6444 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    162
    Rep Power
    2

    Default Re: Another way to add a keylistener to a JComponent?

    You can just have your JFrame class implement KeyListener or KeyAdapter. Then when you add your KeyListener you just do addKeyListener(this);

    Here's an example:
    Java Code:
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;
    
    public class Main extends JFrame implements KeyListener {
    
    	public static void main(String[] args) {
    		new Main();
    	}
    	
    	public Main() {
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setSize(400, 400);
    		setResizable(false);
    		
    		addKeyListener(this);
    		setFocusable(true);
    		
    		setVisible(true);
    	}
    
    	public void keyPressed(KeyEvent e) {
    		int k = e.getKeyCode();
    		if(k == KeyEvent.VK_W) {
    			System.out.println("W");
    		}
    	}
    
    	public void keyReleased(KeyEvent arg0) {}
    	public void keyTyped(KeyEvent arg0) {}
     
    }
    In this code you get a JFrame on your screen, and whenever you press W it prints out W.

    Now, if you don't want all of the KeyListener methods you will have to use KeyAdapter, which I believe is a class and not an interface. So you'd need to create a new class for that. But this is a way to do it all in one class.

  6. #6
    pj6444 is offline Senior Member
    Join Date
    Jan 2013
    Posts
    162
    Rep Power
    2

    Default Re: Another way to add a keylistener to a JComponent?

    And instead of having four different KeyListener classes, you can just do it all in one like this:

    Java Code:
    public void keyPressed(KeyEvent e) {
        int k = e.getKeyCode();
        if(k == KeyEvent.VK_W) {
            // do stuff
        }
        
        if(k == KeyEvent.VK_A) {
            // do stuff
        }
    
        // S and D etc..
    }

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

    Default Re: Another way to add a keylistener to a JComponent?

    Thanks for the replies!

Similar Threads

  1. What is this JComponent?
    By zFollette in forum New To Java
    Replies: 2
    Last Post: 12-27-2013, 06:41 PM
  2. Concurrently writing to a JComponent
    By unaligned in forum Advanced Java
    Replies: 20
    Last Post: 08-05-2011, 11:39 PM
  3. can one disable key bindings on a JComponent?
    By gib65 in forum AWT / Swing
    Replies: 2
    Last Post: 10-14-2010, 04:44 PM
  4. Replies: 2
    Last Post: 10-01-2010, 07:18 PM
  5. SetBackground for JComponent
    By tulasi.neppali in forum AWT / Swing
    Replies: 5
    Last Post: 09-12-2010, 10:14 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
  •