Adding a JPanel to a JMenu - Focus issues
Hi all,
I am working on a requirement and have come across something unexpected.
The expected behaviour when working with menu items is when adding a JMenuItems to a JMenu and making the Menu visible, moving the mouse over each of the items highlights that items and allows each to be selected.
However when I add a JPanel to a JMenu, and the JPanel contains the JMenuItems, these items are no longer highlighted or selectable. Further, when mousing over the contained JMenuItems, focus seems to be lost from the JMenu entirely and the popup disappears altogether.
I've constructed the following code to demonstrate this issue:
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
public class TestMenuItems extends JFrame {
private JPopupMenu _thePopup = new JPopupMenu();
public TestMenuItems() {
this.setLayout( new BorderLayout() );
JPanel thePanel = new JPanel();
this.add( thePanel, BorderLayout.CENTER );
this.addMouseListener( new MouseAdapter(){
public void mousePressed(MouseEvent e) {
_thePopup.show((Component)e.getSource(), e.getX(), e.getY());
}
});
JMenu theMenu = new JMenu("Menu");
_thePopup.add( theMenu );
thePanel.setBackground( Color.BLUE );
thePanel.setLayout( new BorderLayout() );
JPanel theInnerPanel = new JPanel();
theInnerPanel.setLayout( new BoxLayout( theInnerPanel, BoxLayout.X_AXIS ) );
theInnerPanel.add( new JMenuItem("Press 1") );
theInnerPanel.add( new JMenuItem("Press 2") );
theMenu.add(theInnerPanel);
theMenu.add(new JMenuItem("Press 3"));
theMenu.add(new JMenuItem("Press 4"));
}
public static void main( String[] args ){
TestMenuItems theApp = new TestMenuItems();
theApp.setSize( new Dimension(200, 200));
theApp.setLocation(200, 200);
theApp.setVisible( true );
}
}
Does anyone know the reason why this happens and how to make the JMenuItems that are wrapped by the JPanel receive the focus of the mouse. Any idea's?
Just as a reminder, this is a small demonstration of a larger issue I have. I am not interested in how I can perform the same GUI representation using different techniques. Please only respond if you understand what is happening with my example and how to pass the events to the correct components.
Thanks