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.
Fo开发者_如何学运维r 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!
An Action
is well suited for this. See How to Use Actions for more.
AbstractButton.setMnemonic(int)
Just iterate through the range of accepted ints.
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.
精彩评论