5656
5757import javax .swing .Action ;
5858import javax .swing .ImageIcon ;
59+ import javax .swing .JButton ;
5960import javax .swing .JCheckBoxMenuItem ;
6061import javax .swing .JComponent ;
6162import javax .swing .JMenu ;
@@ -188,7 +189,10 @@ static public JMenuItem newJMenuItem(String title, int what) {
188189 */
189190 static public JMenuItem newJMenuItem (Action action , int what ) {
190191 JMenuItem menuItem = new JMenuItem (action );
191- menuItem .setAccelerator (KeyStroke .getKeyStroke (what , SHORTCUT_KEY_MASK ));
192+ // Use putValue() instead of setAccelerator() to work with applyAction()
193+ // menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_KEY_MASK));
194+ action .putValue (Action .ACCELERATOR_KEY ,
195+ KeyStroke .getKeyStroke (what , SHORTCUT_KEY_MASK ));
192196 return menuItem ;
193197 }
194198
@@ -208,7 +212,10 @@ static public JMenuItem newJMenuItemShift(String title, int what) {
208212 */
209213 static public JMenuItem newJMenuItemShift (Action action , int what ) {
210214 JMenuItem menuItem = new JMenuItem (action );
211- menuItem .setAccelerator (KeyStroke .getKeyStroke (what , SHORTCUT_SHIFT_KEY_MASK ));
215+ // Use putValue() instead of setAccelerator() to work with applyAction()
216+ // menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_SHIFT_KEY_MASK));
217+ action .putValue (Action .ACCELERATOR_KEY ,
218+ KeyStroke .getKeyStroke (what , SHORTCUT_SHIFT_KEY_MASK ));
212219 return menuItem ;
213220 }
214221
@@ -514,6 +521,21 @@ static public int getMenuItemIndex(JMenu menu, JMenuItem item) {
514521 }
515522
516523
524+ /**
525+ * Apply an Action from something else (i.e. a JMenuItem) to a JButton.
526+ * Swing is so absof*ckinglutely convoluted sometimes. Do we really need
527+ * half a dozen lines of boilerplate to apply a key shortcut to a button?
528+ */
529+ static public void applyAction (Action action , JButton button ) {
530+ button .setAction (action );
531+ // use an arbitrary but unique name
532+ String name = String .valueOf (action .hashCode ());
533+ button .getActionMap ().put (name , action );
534+ button .getInputMap (JComponent .WHEN_IN_FOCUSED_WINDOW )
535+ .put ((KeyStroke ) action .getValue (Action .ACCELERATOR_KEY ), name );
536+ }
537+
538+
517539 // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
518540
519541
0 commit comments