Search code examples
javaswingjbuttonkeyevent

How to dynamically assig keys to buttons?


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!


Solution

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