What the hell is wrong with this code? Why does the menu not gain the focus and not respond to the key pressed events when the mouse is over it? How does it actually gain the focus? This should be a basic question so I'm optimistic about that someone knows the answer. I probably miss smthing but its quite annoying that those things don't work.
import java.awt.event.*;
import javax.swing.*;
public class KeyListenerTest extends JFrame {
JMenuBar menubar = new JMenuBar();
JMenu open = new JMenu("Open");
JMenuItem file = new JMenuItem("File");
public KeyListenerTest() {
open.add(file);
menubar.add(open);
this.setJMenuBar(menubar);
open.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
System.out.println("mouse pressed");
}
});
open.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
System.out.println("focus gained");
}
});
open.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("key pressed");
}
});
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(100, 100);
setVisible(true);
}
public static void main(String[] args) {
KeyListenerTest test = new KeyListenerTest();
}
}
Edited by: javiator on Jul 30, 2008 6:49 AM