JMenu在Windows7 LAF Java7中使用focuslost事件

如果在单击另一个组件时仍然打开弹出菜单,则该组件不会获取该事件,因为它可能被弹出窗口消耗。 这通常发生在所有JPopupmenus上。 这只发生在带有Windows LAF(Windows7)的Java 7中。 有解决方法吗? 这是一个已知的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); } } 

这是修复问题的神奇线:

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

在查看BasicPopupMenuUI类的源代码后,我发现了这一点。 显然,根据代码中的以下注释,这种行为是一种刻意的设计选择,但它确实对我来说是一个错误。

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

顺便说一句,它也发生在Java 5和6中。