We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,680 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Getting the keylistener to work

hello, hello! im probably being really dumb again, but i can't get java to run keyPressed() when i press a key. do i need to initialize the keylistener somewhere? any input is appreciated!(even if it's not help)

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JPanel;
import javax.swing.Timer;

public class GamePanel extends JPanel implements ActionListener, KeyListener{

    Blocks blocks = new Blocks();
    Player player = new Player();

    public GamePanel(){

        Timer tim = new Timer(50, this);
        tim.start();
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);

    }

    private void update(){

        blocks.update();
        player.update();

    }

    public void paintComponent(Graphics g){

        blocks.paint(g);
        player.paint(g);

    }

    public void actionPerformed(ActionEvent e){

        update();
        repaint();



    }

    // key listeners

    public void keyPressed(KeyEvent e) {

        System.out.println("a down");

    }

    public void keyReleased(KeyEvent e) {



    }

    public void keyTyped(KeyEvent e) {



    }

}

thank you.

2
Contributors
3
Replies
1 Hour
Discussion Span
10 Months Ago
Last Updated
4
Views
Question
Answered
2concussions
Newbie Poster
6 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Has a keylistener been added?

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

what do you mean?

2concussions
Newbie Poster
6 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

What code do you expect to call the KeyListener methods? You have to tell that code to make the calls when there are key events. That's done by adding a key listener to the Component that has the focus.
Take a look at the tutorial:
http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16
Question Answered as of 10 Months Ago by NormR1

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.3099 seconds using 2.71MB