This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Little Book of Impediments (e-book only) and have Tom Perry on-line!
See this thread for details.
Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

keyListener problems

 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I'm trying to set up a key listener in class that extends JPanel.
I have 2 classes, the first extends JApplet, see below:


and then there is the PacmanGame.java class which extends JPanel:



I'm really stuck when it comes to adding the keyListener,
I can do it with MouseListener and MouseMotionListener and ActionListener,
by coding the following into the Constructor.
addMouseMotionListener(this);
addMouseListener(this);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this); for example.

But I can't seem to do it with keyListener, because apparently it
works differently.
Please can someone show me how to accomplish this. Thanks very much for any help.
 
Ulf Dittmer
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What kind of problem do you have adding the KeyListener? What doesn't work according to your expectations?
 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I don't know how to use the
addKeyListener(...)
method.
I know it works differently to MouseListener for example.
Do you know how I can put the addKeyListener into my Constructor, in order
that the methods keyPressed, keyReleased, etc.etc. will be called after a key event has taken place?
 
Ulf Dittmer
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know that it works any differently. What happens when you add it like the other handlers?
 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeh, I've tried it, it nothing happens.
I've managed to get it to work when I'm using a JFrame.
For example in the constructor...

So, I don't really know, I thought it wouldn't be that difficult.
I don't get all this getContentPane stuff. Java annoys me when I
don't understand.
 
tito bayuadji
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can use in your panel to add keylistener
such as


but to make it work the component have to receieve focus, perhaps that's why
the keylistener doesn't work in your case.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic