2

I have many tables in my Java application. When i click "Ctrl + A" in Mac OS X, it selects all rows inside the current table. I wonder if i can change the default shortcut to use "Command + A" instead to select all the rows in the table ?

I am trying to do this inside the EventQueue class to be applied automatically on all the tables in my application.

camickr
  • 321,443
  • 19
  • 166
  • 288
Brad
  • 4,457
  • 10
  • 56
  • 93

3 Answers3

2

Swing uses Key Bindings to map KeyStrokes to Actions. So you can add another binding to map "Command A" to the existing "Control A" binding.

See Key Bindings for more information on how to do this as well as a link to the Swing tutorial on How to Use Key Bindings.

Also, check out How do you refer to the mac command key in the String version of Java's KeyStroke.getKeystroke? for information on how to specify the "command" key in a KeyStroke.

Edit:

... I wanted to do that in the EventQueue class to be applied automatically to all tables i create in my application

Yes, usually Key Bindings are applied to individual components. If you want to change bindings for all components then you need to use the UIManager to access the default InputMap. For a JTable you should be able to use:

InputMap im = (InputMap) UIManager.get("Table.ancestorInputMap");

See UIManager Defaults for more information showing the default InputMap used for each Swing component.

Community
  • 1
  • 1
camickr
  • 321,443
  • 19
  • 166
  • 288
  • But in that case i will have to bind the shortcut to each table in my application, right ? ... I wanted to do that in the EventQueue class to be applied automatically to all tables i create in my application. – Brad Aug 05 '14 at 16:33
  • Thanks a lot camickr :) .. That was very helpful. I will add the final solution that i have used in a new answer below for reference if anyone had the same situation. – Brad Aug 07 '14 at 05:07
2

By default, the "selectAll" action for JTable on Mac OS X is bound to ⌘-A. Instead of using the control key explicitly, use getMenuShortcutKeyMask(), which returns the corresponding Event.META_MASK on Mac OS X and Event.CTRL_MASK on Windows. Some examples are cited here, but here's the basic idea:

int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
KeyStroke.getKeyStroke(KeyEvent.VK_A, MASK)
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

That is the final solution i have used(Thanks to camickr) :

InputMap im = myTable.getInputMap( JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT );
final int CMD_BTN = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
im.put( KeyStroke.getKeyStroke( KeyEvent.VK_A, CMD_BTN ), "selectAll" );
Brad
  • 4,457
  • 10
  • 56
  • 93
  • 1
    You're right. I just didn't know about the "selectAll" or you can say i forgot it :) – Brad Aug 07 '14 at 21:37