Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Adding key listener to jmenu

843806Jul 30 2008 — edited Jul 30 2008
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 27 2008
Added on Jul 30 2008
3 comments
317 views