我已经使用Key Accelerators创建了JMenuItems,然后我将它们直接添加到菜单栏中而无需添加到JMenu中,因此它们看起来像JButtons,每个工作都很好,但我注意到JMenuItem永远不会得到焦点点击或按下键,这给我带来了一些问题,例如: 其中一个JMenuItems用于保存,我也有一个JTextField在失去焦点时进行一些验证,但是当按下Save时无效,焦点保留在JTextField上。
任何想法?!
答案 0 :(得分:0)
我建议使用JToolBar
并利用Action API
这是一个非常简短的示例,说明如何为工具栏(或任何)按钮实现加速器支持。
public class MenuTest {
public static void main(String[] args) {
new MenuTest();
}
public MenuTest() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JToolBar tb = new JToolBar();
tb.add(new FastButton(new OpenAction()));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(tb, BorderLayout.NORTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class FastButton extends JButton {
private FastButton(Action action) {
super(action);
setHideActionText(true);
}
@Override
protected void configurePropertiesFromAction(Action a) {
super.configurePropertiesFromAction(a);
if (a != null) {
KeyStroke ks = (KeyStroke) a.getValue(Action.ACCELERATOR_KEY);
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getActionMap();
inputMap.put(ks, "Action.accelerator");
actionMap.put("Action.accelerator", a);
}
}
}
public class OpenAction extends AbstractAction {
public OpenAction() {
putValue(NAME, "Open");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK));
putValue(SMALL_ICON, new ImageIcon(getClass().getResource("/folder_document.png")));
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Open");
}
}
}