How to add a shortcut key to my plugin menu item?

This topic has been viewed 8854 times and has 2 replies
Thread status: Active
Questions about extending features and developing plug-ins [img]http://www.sweethome3d.com/images/flags/en_small.gif[/img]
Post Reply New Topic
jaffguo
Posts: 3
Joined: Tue Sep 30, 2014 5:38 pm

How to add a shortcut key to my plugin menu item?

Post by jaffguo »

Hi,

I'm wondering if there would be a way to add a shortcut key to my customized plugin menu item.

thanks,

jaff
User avatar
Puybaret
Posts: 9440
Joined: Mon Nov 07, 2005 12:00 pm
Country: Paris, France
Contact:

Re: How to add a shortcut key to my plugin menu item?

Post by Puybaret »

You can add shortcut by binding an instance of KeyStroke with an action that will execute your plugin. The good place to program this should be in the method getActions of your plug-in :

Code: Select all

  public PluginAction [] getActions() {
    final PluginAction pluginAction = new [i]PluginActionClass[/i](...);

    // Create shortcut once Sweet Home 3D window is created
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
          // KeyStroke for shortcut Ctrl+Alt+Shift+C (cmd+alt+shift+C under Mac OS X)
          KeyStroke cmdOrCtrlAltShiftC = KeyStroke.getKeyStroke(KeyEvent.VK_C, 
              Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() 
              | KeyEvent.ALT_DOWN_MASK 
              | KeyEvent.SHIFT_DOWN_MASK);
          // Bind shortcut with the key "MY_KEY"
          JComponent homePane = (JComponent)getHomeController().getView();
          String actionKey = "MY_KEY";
          homePane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).
              put(cmdOrCtrlAltShiftC, actionKey);
          // Bind the key "MY_KEY" with an action that will execute the plug-in
          homePane.getActionMap().put(actionKey, new AbstractAction() {
              public void actionPerformed(ActionEvent e) {
                pluginAction.execute();
              }
            });
          
        }
      });

    return new PluginAction [] {pluginAction};
  }
If you want that the shortcut appears beside the menu item of the plug-in, you'll have to find the menu item in the menu bar returned by

Code: Select all

((JFrame)SwingUtilities.getWindowAncestor((JComponent)getHomeController().getView())).
  getJMenuBar();
with [font=courier new]getMenu[/font] then [font=courier new]getMenuComponent[/font] methods. Once you found the right menu item, just call its setAccelerator method.
Emmanuel Puybaret, Sweet Home 3D creator
jaffguo
Posts: 3
Joined: Tue Sep 30, 2014 5:38 pm

Re: How to add a shortcut key to my plugin menu item?

Post by jaffguo »

I very much appreciate your help, Ennanuel. It works well. Thanks a lot.
Jaff
Post Reply New Topic

Who is online

Users browsing this forum: No registered users and 2 guests