5

I have a section in my GUI that is generated dynamically according to a list of objects. So, for each object in that list I want to create a JButton and associate a keyboard shortcut.

For example:

for (String tag : testTags) {
    new JButton(tag).setMnemonic(KeyEvent.VK_F1);
}

How do I make the code "setMnemonic(KeyEvent.VK_F1)" dynamic in an elegant way? Is there some way to get a range of keys automatically and then use it in this iteration?

Thanks!

ktulinho
  • 3,870
  • 9
  • 28
  • 35

3 Answers3

4

An Action is well suited for this. See How to Use Actions for more.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2
AbstractButton.setMnemonic(int)

Just iterate through the range of accepted ints.

Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
2

Either create an array containing your Keys with

int[] keys = {KeyEvent.VK_F1,KeyEvent.VK_F2,[...]};

or iterate over the range of the F1-F12 keys (112 - 123)

int key = KeyEvent.VK_F1;
for (String s : strings) {
    new JButton(s).setMnemonic(key++);
}

You do have to check if key is still in range (123 being F12), though.

vehk
  • 926
  • 7
  • 7