JMenuItem未通过键盘输入键激活

时间:2012-06-22 19:12:14

标签: java macos swing unix jmenuitem

我自动生成一组JMenuItem,并在每次右键单击事件中将它们添加到JPopUpMenu。问题是当我按下所选菜单上的回车键时,我为菜单项设置的操作不会运行。我可以使用向上/向下键在菜单上导航,但是,只能通过鼠标单击来执行操作。

以下是创建菜单项的代码:

private JMenuItem createMenuItem(TaskFactory tf, String title, boolean useCheckBoxMenuItem, String toolTipText) {

    enter code hereJMenuItem item;
    PopupAction action = new PopupAction(tf, title);
    if ( useCheckBoxMenuItem )
        item = new JCheckBoxMenuItem(action);
    else
        item = new JMenuItem(action);
    item.setEnabled(tf.isReady());
    item.setToolTipText(toolTipText);
    return item;
}

private class PopupAction extends AbstractAction {

    TaskFactory tf;
    PopupAction(TaskFactory tf, String title) {
        super( title );
        this.tf = tf;
    }
    public void actionPerformed(ActionEvent ae) {
        m_view.manager.execute(tf.createTaskIterator());
    }
}

我尝试将焦点设置为true,但这不起作用。我在Mac 10.7上尝试过Java版本1.6.0_33和Ubuntu Java版本1.6.0_26。我使用了标准的摇摆外观和感觉。在Mac上运行时:外观和感觉是[适用于Mac OS X的Aqua Look and Feel - com.apple.laf.AquaLookAndFeel]

4 个答案:

答案 0 :(得分:2)

Windows XP,JDK6_025,使用Substance,Metal,Windows,Nimbus

EDIT1

按下的键或鼠标被触发isEnabled

Edit2

添加MenuKeyListener

通知!!!!!

不要使用MenuKeyListener来抓取另一个KeyEvents (空格)和,否则会产生虚假结果,例如Unknown keyCode: 0x0 on …

import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.MenuKeyEvent;
import javax.swing.event.MenuKeyListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.table.*;
import org.pushingpixels.substance.api.SubstanceLookAndFeel;
import org.pushingpixels.substance.api.skin.BusinessBlueSteelSkin;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        createPopupMenu();
    }

    private void createPopupMenu() {
        MyMenuKeyListener myMenuKeyListener = new MyMenuKeyListener();
        JPopupMenu popup = new JPopupMenu();
        JMenuItem myMenuItem1 = new JMenuItem("cccccccccccccccccccccc");
        myMenuItem1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                //System.out.println("Done myMenuItem1");
            }
        });
        myMenuItem1.getModel().addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                ButtonModel model = (ButtonModel) e.getSource();
                if (model.isArmed()) {
                    //System.out.println("isArmed");
                } else if (model.isEnabled()) {
                    //System.out.println("isEnabled");
                } else if (model.isPressed()) {
                    //System.out.println("isPressed");
                } else if (model.isRollover()) {
                    //System.out.println("isRollover");
                } else if (model.isSelected()) {
                    //System.out.println("isSelected");
                }
            }
        });
        myMenuItem1.addMenuKeyListener(myMenuKeyListener);

        JMenuItem myMenuItem2 = new JMenuItem("bbbbbbbbbbbbbbbbbbbbbb");
        myMenuItem2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                //System.out.println("Done myMenuItem2");
            }
        });
        myMenuItem2.getModel().addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                ButtonModel model = (ButtonModel) e.getSource();
                if (model.isArmed()) {
                    //System.out.println("isArmed");
                } else if (model.isEnabled()) {
                    //System.out.println("isEnabled");
                } else if (model.isPressed()) {
                    //System.out.println("isPressed");
                } else if (model.isRollover()) {
                    //System.out.println("isRollover");
                } else if (model.isSelected()) {
                    //System.out.println("isSelected");
                }
            }
        });
        myMenuItem2.addMenuKeyListener(myMenuKeyListener);

        popup.add(myMenuItem1);
        popup.add(myMenuItem2);
        MouseListener popupListener = new PopupListener(popup);
        table.addMouseListener(popupListener);
        popup.setLightWeightPopupEnabled(false);
        PopupMenuListener popupMenuListener = new MyPopupMenuListener();
        popup.addPopupMenuListener(popupMenuListener);
    }

    private class PopupListener extends MouseAdapter {

        private JPopupMenu popup;

        PopupListener(JPopupMenu popupMenu) {
            popup = popupMenu;
        }

        @Override
        public void mousePressed(MouseEvent e) {
            maybeShowPopup(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (table.getSelectedRow() != -1) {
                maybeShowPopup(e);
            }
        }

        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }
    }

    private class MyMenuKeyListener implements MenuKeyListener {

        public void menuKeyTyped(MenuKeyEvent e) {
            MenuElement[] path = e.getPath();
            JMenuItem item = (JMenuItem) path[path.length - 1];
            System.out.println("Key typed: " + e.getKeyChar()
                    + ", " + MenuKeyEvent.getKeyText(e.getKeyCode())
                    + " on " + item.getText());
        }

        public void menuKeyPressed(MenuKeyEvent e) {
            MenuElement[] path = e.getPath();
            JMenuItem item = (JMenuItem) path[path.length - 1];
            System.out.println("Key typed: " + e.getKeyChar()
                    + ", " + MenuKeyEvent.getKeyText(e.getKeyCode())
                    + " on " + item.getText());
        }

        public void menuKeyReleased(MenuKeyEvent e) {
            MenuElement[] path = e.getPath();
            JMenuItem item = (JMenuItem) path[path.length - 1];
            System.out.println("Key typed: " + e.getKeyChar()
                    + ", " + MenuKeyEvent.getKeyText(e.getKeyCode())
                    + " on " + item.getText());
        }
    }

    private class MyPopupMenuListener implements PopupMenuListener {

        public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
            //System.out.println("Canceled");
        }

        public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
            //System.out.println("Becoming Invisible");
        }

        public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
            //System.out.println("Becoming Visible");
        }
    }

    public static void main(String[] args) {
        /*SwingUtilities.invokeLater(new Runnable() {

        public void run() {
        SubstanceLookAndFeel.setSkin(new BusinessBlueSteelSkin());
        }
        });*/
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
            /*UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());*/
        } catch (ClassNotFoundException ex) {
        } catch (InstantiationException ex) {
        } catch (IllegalAccessException ex) {
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        }
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

答案 1 :(得分:1)

AFAIK,这就是外观的感觉。按空格键可以单击按钮和菜单项。 Enter表示单击默认按钮。

答案 2 :(得分:1)

对于添加到菜单栏的所有项目以及通过Action添加到上下文菜单中的项目,此ImageApp似乎可以正常使用setComponentPopupMenu() Enter Space 从菜单栏或上下文菜单中唤起所选菜单项。

另外,请注意使用getMenuShortcutKeyMask()作为跨平台MASK

答案 3 :(得分:0)

您需要将KeyListener添加到JMenuItem,并将该项设置为focusable。让您的JMenuItem请求焦点

JMenuItem.requestFocus();

当它具有焦点时,实现很容易

在你的keylistener中:

        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == e.VK_ENTER) {
                // do stuff
            }

        }