Frage

I am trying to consolidate most of my menus in 2 similar applications that share a lot of classes. Part of this is I am trying to move anything I can into actions. The issue I am running into is I want the same accelerators for the menu items. Is there a way I can set this in the action so that I don't have to duplicate my code for setting the accelerator?

package com.protocase.viewer.actions;

import com.protocase.viewer.DesignerApplication;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import static javax.swing.Action.MNEMONIC_KEY;
import static javax.swing.Action.SHORT_DESCRIPTION;


/**
 *
 * @author davidh
 */
public class NewEnclosureAction extends AbstractAction{

    private DesignerApplication app;

    public NewEnclosureAction(DesignerApplication app) {
        super();
        this.app = app;
        putValue(SHORT_DESCRIPTION, "New");
        putValue(AbstractAction.NAME, "New");
        putValue(MNEMONIC_KEY, KeyEvent.VK_N);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
       app.OnNew();
    }

}

..........

    JMenuItem newMit = new JMenuItem(new NewEnclosureAction(this));
    newMit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.ALT_MASK));
    newMit.getAccessibleContext().setAccessibleDescription("New Enclosure from template");
    fileMenu.add(newMit);

..........

I am looking to move the setAccelerator calls to within my action class.

Is there any way to do this?

War es hilfreich?

Lösung

There's a value for accelerator keys like for the short description, that would, for you case, be written like this :

    putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.ALT_MASK));

If you use Eclipse as IDE, it should tell you the available keys when typing putValue and hitting the auto-complete shortcut.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top