Skip to main content

addKeyListener() does not working unless listener added to JFrame

2 replies [Last post]
herthh
Offline
Joined: 2009-08-14
Points: 0

Imagine
public class Any extends JPanel implements KeyListener, MouseListener
{
public Any()
{
addKeyListener(this);
addMouseListener(this);
...etc
}
....
/* contains all necessary listener implementations */
}

That panel can be added to JFrame and mouse listener works as expected and usual, but not the key listener. In order to get the key listener to work, I have to add the listener to the Frame itself:

Any any=new Any();
JFrame F=new JFrame();
F.add(any);
F.addKeyListener(any);

Is it a bug? I find no explanation in Java Doc's...

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
walterln
Offline
Joined: 2007-04-17
Points: 0

KeyEvent are dispatched to focusable components only. Perhaps using KeyBindings is better suited to your problem.

herthh
Offline
Joined: 2009-08-14
Points: 0

Actually I found some details about this ordeal with key listener: It is related to the focus handler.

Ultimately what helped was to call requestFocusInWindow() in mouse handler, like this:

[b] public void mouseEntered (MouseEvent e)
{
...do your stuff...
requestFocusInWindow(); // call the magic function to make KeyListener alive
}[/b]

I also called setFocusable(true); in constructor and /or added isFocusable () { return true; } but all this could have been removed. Add the listener and call reqFocusInWindow upon mouse entry does the trick.

Thomas