JMenu在Windows7 LAF Java7中使用focuslost事件 [英] JMenu consumes focuslost event in Windows7 LAF Java7

查看:109
本文介绍了JMenu在Windows7 LAF Java7中使用focuslost事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果单击另一个组件时弹出菜单仍处于打开状态,则该组件不会获取事件,因为该事件可能已被弹出窗口占用.通常,所有JPopupmenus都会发生这种情况. 仅在具有Windows LAF(Windows7)的Java 7中会发生这种情况.有解决方法吗?这是一个已知的错误吗?

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);           
    }
}

推荐答案

这是解决问题的神奇方法:

Here is the magic line that fixes the problem:

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

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

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.

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

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

这篇关于JMenu在Windows7 LAF Java7中使用focuslost事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆