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

    Default problem with KeyListener

    I wrote a keylistener to move my character around the screen, then attempted to add it to my frame. I did not get any errors, but the figure is not moving when I press the keys I specified. There are three classes: a listener class for my game, the class that paints a ball and the image, and the main class to create the JFrame.

    The keylistener (kw) is in the ballpanel class line 23

    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class MyListener extends BallPanel implements ActionListener{
    		
    	private BallPanel ballPanel;
    	
    	public MyListener(BallPanel ballPanel){
    		this.ballPanel = ballPanel;
    	}
    
    	public void actionPerformed(ActionEvent e) {
    		count++;
    		ballPanel.step();
    	}
    }
    Java Code:
    import java.awt.BorderLayout;
    
    import javax.swing.JFrame;
    import javax.swing.Timer;
    
    public class Main extends BallPanel{
     
        public static void main(String[] args) {
        	Main m = new Main();
        	JFrame frame = new JFrame("Counter");
        	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        	frame.setLayout(new BorderLayout());
        	
        	BallPanel ballPanel = new BallPanel();
        	frame.add(ballPanel, BorderLayout.CENTER);
        	frame.addKeyListener(m.kw);
    		ballPanel.addKeyListener(m.kw);
    
        	//pass the BallPanel instance into the MyListener constructor
        	MyListener listener = new MyListener(ballPanel);
        	
        	//the timer fires 30 times a second
        	Timer timer = new Timer(1000/30, listener);
        	
        	//start the timer
        	timer.start();
        	frame.setSize(500, 500);
        	frame.repaint();
        	frame.setVisible(true);
        	
        	
        }
    }
    Java Code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.image.BufferedImage;
    import java.io.File;
    
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
    
    
    public class BallPanel extends JPanel{
    	
    	private int ballX = 250;
    	public int count;
    	private int ballY = 250;
    	private int ballDiameter = 50;
    	private BufferedImage image1;
    	private double ballXSpeed = 5;
    	private double ballYSpeed = 10;
    	public int peterx;
    	public int petery;
    	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_UP) {
    				petery = petery - 10;
    				repaint();
    			}		
    			if (k == KeyEvent.VK_DOWN) {
    				petery = petery + 10;
    				repaint();
    			}	
    			if (k == KeyEvent.VK_LEFT) {
    				peterx = peterx - 10;
    				repaint();
    			}
    			if (k == KeyEvent.VK_RIGHT) {
    				peterx = peterx + 10;
    				repaint();
    			}
    		}
    
    		@Override
    		public void keyReleased(KeyEvent e) {
    			// TODO Auto-generated method stub
    			
    		}
    		
    	};
    	
    	public BallPanel(){
    		setBackground(Color.BLACK);
    		try {
    			image1 = ImageIO.read(new File(
    					"/Users/MW/Downloads/petergriffin2.png"));
    		} catch (Exception e) {
    			System.out.println("could not load img");
    		}
    	}
    	
    	//call this method from a Timer to move the ball!
    	public void step(){
    		
    		//move the ball on the X axis
    		ballX += ballXSpeed;
    		//if the ball goes off the edge, bounce it by reversing its speed
    		if(ballX < 0 || ballX > getWidth()-ballDiameter){
    			ballXSpeed *= -1;
    		}
    		
    		//move the ball on the Y axis
    		ballY += ballYSpeed;
    		//if the ball goes off the edge, bounce it by reversing its speed
    		if(ballY < 0 || ballY > getHeight()-ballDiameter){
    			ballYSpeed *= -1;
    		}
    		
    		//tell this JPanel to repaint itself since the ball has moved
    		repaint();
    	}
    	
    	//paint the ball
    	public void paintComponent(Graphics g){
    		
    		super.paintComponent(g);
    		g.drawImage(image1,peterx,petery,null);
    		g.setColor(Color.BLUE);
    		g.fillOval(ballX, ballY, ballDiameter, ballDiameter);
    		g.setColor(Color.white);
    		g.drawString(Integer.toString(count),350,50);
    		repaint();
    		
    	}
    
    }

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

    Default Re: problem with KeyListener

    Try adding some printlns to the keylistener to see if it is even getting events.

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

    Default Re: problem with KeyListener

    Hi.
    Yes, it is getting the events. It printed the statements.

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

    Default Re: problem with KeyListener

    Ok, it looks to me like you are calling the repaint() method from JPanel after every event. Try calling step()
    EDIT: Is the actionlistener getting events?

    Instead of adding/subtracting like this:
    Java Code:
    petery = petery - 10;
    Do it like this:
    Java Code:
    petery -= 10
    Last edited by zFollette; 01-22-2014 at 07:37 AM.

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

    Default Re: problem with KeyListener

    But Step is just for the ball movement. The actionListeners are for my actual image of a figure (peter griffin) to move, so they're independent of each other.

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

    Default Re: problem with KeyListener

    Actually, either way is perfectly acceptable. And if you forget the order and do the following:

    Java Code:
    petery =- 10;
    Then you have just assigned the value -10 to petery and the compiler will not complain because it's legit.

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

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,900
    Rep Power
    5

    Default Re: problem with KeyListener

    Still strange that the ball does not move though, I'd expect it to suddenly partially or entirely disappear off of the screen as soon as you press a button with that tiny bug in there.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

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

    Default Re: problem with KeyListener

    Try printing out the coordinates of the ball. Maybe something is causing it not to change.

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

    Default Re: problem with KeyListener

    Why are you calling repaint() from paintComponent()? You should not do that. And why is your listener extending BallPanel? You subclass a class to add functionality to it. Yet I see no additional functionality in MyListener that is derived from BallPanel. Which is also why your count is not updating. You are updating the count variable in the instantiation associated with your Listener. So you need to get rid of your "extends BallPanel" in your listener and use the ballPanel reference to update your count. Finally, get rid of the extends BallPanel in your Main class. Use the created ballPanel instance in main to add your keylistener. You simply had too many extraneous instances of BallPanel floating around. And you were changing values in ones that didn't make a difference.

    And once again, I will urge you to take a break from this and read the tutorials. Especially on listeners (the whole EDT in general) and painting.

    Regards,
    Jim
    Last edited by jim829; 01-22-2014 at 08:53 PM.
    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: problem with KeyListener

    I got it. What fixed it was adding ballPanel.listener();

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

    Default Re: problem with KeyListener

    It's not "fixed" unless you at least do the other stuff I told you about (and even then there may be problems I didn't find). Get rid of the extends I mentioned and get rid of repaint in the paintComponent method.

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

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

    Default Re: problem with KeyListener

    Quote Originally Posted by jim829 View Post
    It's not "fixed" unless you at least do the other stuff I told you about (and even then there may be problems I didn't find). Get rid of the extends I mentioned and get rid of repaint in the paintComponent method.

    Regards,
    Jim
    Explanation: Calling repaint() in the paintComponent method triggers an infinite loop, since repaint() calls on the paintComponent() method.
    1000011 1100001 1101110 100000 1111001 1101111 1110101 100000 1110010 1100101 1100001 1100100 100000 1000010 1101001 1101110 1100001 1110010 1111001 111111

Similar Threads

  1. A problem with KeyListener
    By Reskaillev in forum New To Java
    Replies: 4
    Last Post: 07-22-2011, 02:29 AM
  2. KeyListener Graphics Problem
    By Makesfolkslose in forum New To Java
    Replies: 2
    Last Post: 05-26-2011, 04:07 AM
  3. Problem with Keylistener, some help pls
    By syon in forum AWT / Swing
    Replies: 1
    Last Post: 01-21-2011, 01:31 AM
  4. AWT KeyListener Problem
    By plm-pusik in forum New To Java
    Replies: 15
    Last Post: 11-10-2010, 03:38 PM
  5. KeyListener problem
    By siyi90 in forum AWT / Swing
    Replies: 7
    Last Post: 02-08-2010, 10:16 AM

Posting Permissions

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