Results 1 to 9 of 9
  1. #1
    sim18 is offline Member
    Join Date
    Oct 2011
    Posts
    30
    Rep Power
    0

    Default Help with keyListener please

    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.image.BufferedImage;
    
    
    public class PersonAnimationPanel extends JPanel implements ActionListener, KeyListener{
    	
    	public Game parentRef;
    	private Graphics graphic;
    	public MyTimer t;
    	
    	int x = 50, y = 50, velX = 0, velY = 0;
    	
    		
    	public PersonAnimationPanel(Game parentRef)
    	{
    		
    		this.parentRef=parentRef;
    		setPreferredSize(new Dimension(630,450));
    		setBackground(Color.gray);
    		
    		setRequestFocusEnabled(true);
    		setFocusable(true);
    		requestFocusInWindow();
    		addKeyListener(this);
    		setFocusTraversalKeysEnabled(false);
    		grabFocus();
    	}
    	
    	public void paintComponent(Graphics g)
    	{
    		super.paintComponent(g);
    		graphic = g;
    		g.setColor(Color.RED);
    		g.fillRect(x, y, 50, 30);
    	}
    	
    	
    	public void actionPerformed(ActionEvent e){
        	repaint();
        	x += velX;
        	y += velY;
        }
        
        public void up() {
        	velY = -1;
        	velX = 0;
        }
        
        public void down() {
        	velY = 1;
        	velX = 0;
        }
        
        public void left() {
        	velX = -1;
        	velY = 0;
        }
        
        public void right() {
        	velX = 1;
        	velY = 0;
        }
        
    
    	@Override
    	public void keyReleased(KeyEvent arg0) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public void keyTyped(KeyEvent arg0) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public void keyPressed(KeyEvent arg0) {
    		// TODO Auto-generated method stub
    		int code = arg0.getKeyCode();
        	if(code == KeyEvent.VK_KP_UP){
        		up();
        	}
        	if(code == KeyEvent.VK_KP_DOWN){
        		down();
        	}
        	if(code == KeyEvent.VK_LEFT){
        		//left();
        		System.out.println("PRESSED LEFT");
        	}
        	if(code == KeyEvent.VK_KP_RIGHT){
        		right();
        	}
        	if(code == KeyEvent.VK_KP_LEFT){
        		//left();
        		System.out.println("PRESSED LEFT");
        	}
    	}
    }
    Hi, I have this that extends a JPanel, and I have drawn a rectangle on the screen and now I need to use my arrow keys to move the rectangle up, down, left and right. I also added a System.out.println to see if it could listen but no luck! For some reason it is not working and I cannot figure out why. I searched online and it said something about needing to focus on the JPanel and that is why I have tried:

    Java Code:
    setRequestFocusEnabled(true);
    		setFocusable(true);
    		requestFocusInWindow();
    		addKeyListener(this);
    		setFocusTraversalKeysEnabled(false);
    		grabFocus();
    None of these work however. Does anybody have any suggestions?

    Thank you

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Help with keyListener please

    It looks to me like it should work.

    Post a runnable version - ie remove the Game and MyTimer references, and the unused graphic, and add a main() method. [Edit] In fact you could remove up(), down(), etc until you have the key stuff doing what you wanted. Your idea of using System.out.println() is a good one. Personally I'd put System.out.println(arg0) right at the top of the method to make sure it does get called at all.

    ---

    I'll move this to the Swing forum, the better for it to be seen by db or camickr. (And any other of that large number who know more about Swing than I do.)
    Last edited by pbrockway2; 04-30-2013 at 11:19 PM.

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

    Default Re: Help with keyListener please

    Did you add the panel to a frame? Post your Short, Self Contained, Correct Example that demonstrates the problem.

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

    Default Re: Help with keyListener please

    If I am having trouble receiving events, I always put a print statement at the beginning of my listener method (including the dummy methods, just to be sure). Also, in a recent post, I helped someone with keyListener. I found out all I had to do was setFocusable(true) to get the focus. It worked for me. Unfortunately I can't provide a linke to the post at this time.

    And for what its worth, you didn't add your actionListener to your panel.

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

  5. #5
    sim18 is offline Member
    Join Date
    Oct 2011
    Posts
    30
    Rep Power
    0

    Default Re: Help with keyListener please

    Thanks for all of the replies :)
    I've added the main method, and now the System.out.prinln's do work, it's showing me that I have pressed the arrow keys and now the image will move across the screen how I want it.

    But how do I incorporate that into my other code :/

    Here is the updated code that will run:

    Java Code:
    public class PersonAnimationPanel extends JPanel implements ActionListener, KeyListener {
    
    	Timer t = new Timer(5, this);
    	int x = 50, y = 50, velX = 0, velY = 0;
    	private Graphics graphic;
    	
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		PersonAnimationPanel s = new PersonAnimationPanel();
    		JFrame f = new JFrame();
    		f.add(s);
    		f.setVisible(true);
    		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		f.setSize(600, 400);
    	}
    	
    	public PersonAnimationPanel() {
    		t.start();
    		addKeyListener(this);
    		setFocusable(true);
    		setFocusTraversalKeysEnabled(false);
    	}
    	
    	public Graphics getGraphic()
    	{
    		return graphic;
    	}
    	
    	public void paintComponent(Graphics g)
    	{
    		super.paintComponent(g);
    		graphic = g;
    		g.setColor(Color.RED);
    		g.fillRect(x, y, 50, 30);
    	}
    	
    	public void actionPerformed(ActionEvent e){
        	repaint();
    		x += velX;
        	y += velY;
        }
        
        public void up() {
        	velY = -1;
        	velX = 0;
        }
        
        public void down() {
        	velY = 1;
        	velX = 0;
        }
        
        public void left() {
        	velX = -1;
        	velY = 0;
        }
        
        public void right() {
        	velX = 1;
        	velY = 0;
        }
        
    
    	@Override
    	public void keyReleased(KeyEvent arg0) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public void keyTyped(KeyEvent arg0) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public void keyPressed(KeyEvent arg0) {
    		// TODO Auto-generated method stub
    		System.out.println(arg0);
    		int code = arg0.getKeyCode();
        	if(code == KeyEvent.VK_KP_UP){
        		up();
        	}
        	if(code == KeyEvent.VK_DOWN){
        		down();
        	}
        	if(code == KeyEvent.VK_LEFT){
        		//left();
        		System.out.println("PRESSED LEFT");
        	}
        	if(code == KeyEvent.VK_RIGHT){
        		right();
        	}
    	}
    }
    Last edited by sim18; 05-01-2013 at 11:14 AM.

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default Re: Help with keyListener please

    OK, so you've shown this JPanel works as expected when adding it to a Jframe/
    So how are you adding it to a JFrame in your other code that wasn't working?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    sim18 is offline Member
    Join Date
    Oct 2011
    Posts
    30
    Rep Power
    0

    Default Re: Help with keyListener please

    Basically I have it connected to a 'prentRef'

    Java Code:
    public class Game extends JFrame{
    
    	private PersonAnimationPanel myPersonAnimationPanel = new PersonAnimationPanel(this);
    	
    	private FileIO slFile = new FileIO(this);
    	
    	public Game()
    	{
    		setSize(850,600); 
    		setResizable(false);
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setLocationRelativeTo(null); // make the window open in the centre of screen
    		
    		Container cp = getContentPane();	
    		cp.setLayout(new FlowLayout());
    		cp.add(myPersonAnimationPanel);
    and in MyPersonAnimationPanel i use :

    Java Code:
    public PersonAnimationPanel(Game parentRef)
    	{
    		this.parentRef=parentRef;
    		setPreferredSize(new Dimension(630,450));
    		setBackground(Color.gray);
    This sets a JPanel inside the Game container. I need this because I have another Panel inside that.

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,949
    Rep Power
    19

    Default Re: Help with keyListener please

    Anther JPanel inside what?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    sim18 is offline Member
    Join Date
    Oct 2011
    Posts
    30
    Rep Power
    0

    Default Re: Help with keyListener please

    Quote Originally Posted by Tolls View Post
    Anther JPanel inside what?


    I think it inside another JPanel which is then inside the JFrame

Similar Threads

  1. Keylistener
    By dyelax in forum New To Java
    Replies: 4
    Last Post: 09-20-2012, 07:06 PM
  2. Help with KeyListener
    By armyson in forum New To Java
    Replies: 1
    Last Post: 11-25-2011, 12:56 PM
  3. Help with keylistener?
    By Kaizo in forum New To Java
    Replies: 4
    Last Post: 12-11-2010, 12:55 AM
  4. keyListener not doing anything
    By imorio in forum AWT / Swing
    Replies: 10
    Last Post: 08-17-2010, 10:46 PM
  5. KeyListener - Is this what I need?
    By dbashby in forum New To Java
    Replies: 26
    Last Post: 04-18-2009, 04: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
  •