How to dynamically assig keys to buttons?
Asked Answered
R

3

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!

Remove answered 17/6, 2011 at 18:24 Comment(0)
I
4

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

Intelligentsia answered 17/6, 2011 at 19:28 Comment(2)
In the long run, this is the best way to go.Alida
Oh, nice. I actually didn't know about actions. This seems to solve my problem! Thanks!Remove
D
2
AbstractButton.setMnemonic(int)

Just iterate through the range of accepted ints.

Donothingism answered 17/6, 2011 at 18:28 Comment(1)
Something like: int key = 112; new JButton(tag).setMnemonic(key++) ?Remove
A
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.

Alida answered 17/6, 2011 at 19:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.