我正在尝试将我的大部分菜单合并到两个共享许多类的类似应用程序中。其中一部分原因是我正在努力将一切可以采取的行动付诸行动。我遇到的问题是我想要菜单项使用相同的加速器。有没有办法可以在操作中设置它,这样我就不必重复设置加速器的代码?
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);
......
我希望将 setAccelerator 调用移至我的操作类中。
有什么办法可以做到这一点吗?
最佳答案
加速键有一个值,例如简短描述,对于您的情况,可以这样写:
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.ALT_MASK));
如果您使用 Eclipse 作为 IDE,它应该会在您输入 putValue
并点击自动完成快捷键时告诉您可用的键。
关于java - 如何在操作中设置按键的加速器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18389674/