[java] Read keyboard in Swing?

Started by
1 comment, last by GameDev.net 17 years, 4 months ago
I am developing a Swing program for administration, wherein I have a JTabbedPane. On each tabb there is some buttons and labels to read values and show values. Now I want to use "1" to show the first tabb and "2" to show the second tabb, etc. I can not get it to work correctly and would appreciate some pointers. Game programmers must be real experts on reading the keyboard, i reckon. My approach now, is something like this: JFrame... Constructor: ... private JTabbedPane GUIwindow = setupMainTabbPanel (); this.getContentPane ().add (GUIwindow); KeyActionListener listener = new KeyActionListener (GUIwindow); GUIwindow.addKeyListener (listener); ... KeyActionListener::keyReleased (Keyevent arg0) { .... if (KeyEvent.getKeyText (arg0.getKeyCode ()).equals ("F1")) GUIwindowTabbPane.setSelectedIndex (0); else if (KeyEvent.getKeyText (arg0.getKeyCode ()).equals ("F2")) GUIwindowTabbPane.setSelectedIndex (1); ... } This works, if I press "2" the second tabb shows, etc. The problem is that when I input values, the "1","2",... keys stop working. It feels almost as if the tabb panel where i input values still has the focus for all keyboard input? I dont know really. How to solve this problem in an easy manner? Any suggestions?
Advertisement
woa.. calm down.

First just a simplification: you can simply compare the keycode directly with the defined key value instead of converting it to string and then doing a string comparison.

Second you are detecting F1 and F2 but then saying you are pressing 1 and 2, Im going to assume that this is just a typo and assume all is correct.

Finally you are setting the correct tab by changing its visual position in the screen.
What you arent doing is resetting the focus on the tab.
I cant really test it at the moment but Im bettting you press the key (F1 or 1 or whatever) and then trigger your tab change but the focus remains wherever it was.
Try reseting the focus on an edit inside this tab and see if that solves your problem

Yours Truly
K
Pain is Inevitable, Suffering is Optional.Unknown
Ok, thanx for your tip. I will try setting the focus and changing the visual position.

Meanwhile, as I couldnt get it to work, I have discovered an alternate way:

...
Inputmap.put (KeyStroke.getKeystroke ("F1"));
...

What is the difference between my way, and using Inputmaps? Are there any difference? Why are there two ways to read the keyboard? *confused*

This topic is closed to new replies.

Advertisement