JMenu consumes focuslost event in Windows7 LAF Java7

梦想与她 提交于 2019-12-19 10:42:26

问题


If a popup menu is still open when another component is clicked, then the component does not get the event, because it's probably consumed by the popup. This happens for all JPopupmenus in general. This happens only in Java 7 with windows LAF (Windows7). Is there a workaround? Is it a known bug?

import javax.swing.*;
import java.awt.event.*;

public class Test
{
    public static void main(String[] s)
    throws Exception
    {
           String lookAnfFeelClassName = UIManager.getSystemLookAndFeelClassName();
           UIManager.setLookAndFeel(lookAnfFeelClassName);

           JMenu menu = new JMenu("TEST Menu");
           JMenuItem menuItem = new JMenuItem("Menu Item 1");

           JMenuBar menuBar = new JMenuBar();
           menu.add(menuItem);
           menuBar.add(menu);

           final JButton b = new JButton("Test");
           b.setBounds(5, 50, 60, 20);
           b.addActionListener(new ActionListener()
           {
                  public void actionPerformed(ActionEvent e)
                  {
                        //If the Menu is open when I press the button, the putton is not pressed 
                        //so I have to press it again. 
                        JOptionPane.showMessageDialog(b, "Button Pressed");
                  }
           }
           );

           JFrame frame = new JFrame();
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setSize(150, 150);
           frame.setJMenuBar(menuBar);
           frame.getContentPane().setLayout(null);
           frame.getContentPane().add(b);
           frame.setVisible(true);           
    }
}

回答1:


Here is the magic line that fixes the problem:

UIManager.put("PopupMenu.consumeEventOnClose", Boolean.FALSE);

I found this after looking into the source code for the BasicPopupMenuUI class. Apparently this behaviour is a deliberate design choice according to the following comments in the code, but it sure feels like a bug to me.

            // Ask UIManager about should we consume event that closes
            // popup. This made to match native apps behaviour.

By the way, it happens in Java 5 and 6 too.



来源:https://stackoverflow.com/questions/12251161/jmenu-consumes-focuslost-event-in-windows7-laf-java7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!