Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd suggest using a <code>JToolBar</code> and taking advantage of the Action API</p> <p>Here's a really short example of how you might be able to achieve accelerator support for toolbar (or any) button.</p> <pre><code>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"); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload