Sign in to follow this  
kebabbert

[java] Read keyboard in Swing?

Recommended Posts

kebabbert    122
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?

Share this post


Link to post
Share on other sites
BloodWarrior    164
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

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
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*

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this