![]() |
| ||
| extends JFrame implements KeyListener I'm trying to add a KeyListener to my JFrame, but it doesn't seem to work when I have a JButton floating around import java.awt.event.KeyEvent; pressing 'r' should show "reset" in the console try removing the comment "//" tag from this line: //add(new JButton("hi"));now pressing 'r' stops showing "reset"...... Now, I understand adding the KeyListener to the JButton would solve my problem in this tiny case, but if I have multiple JButtons hanging around (not just 1), I'd have to add the KeyListener to every single JButton in case either one of them got the focus last... I'm just not keen to this idea... ---I'm trying to get the entire window to listen for when I press 'r', not just the JButton (s)... I always thought "addKeyListener(this);" would bind the listening to the entire JFrame, but it seems to loose focus if a JButton is around.. Any suggestions? |
| ||
| Re: extends JFrame implements KeyListener Quote:
Just add this code before setting your JFrame visibility setFocusable(true);before your setVisible(true);call. |
| ||
| Re: extends JFrame implements KeyListener Yes, focus issues can be a pain with key listeners. The InputMap and ActionMap make it easier to handle this. Try using this instead of the KeyListener. private void launch() { |
| ||
| Re: extends JFrame implements KeyListener Thanks you two..... I used setFocusable(true); for the JFrame and setFocusable(false); for the JButtons Now my JFrame is always in focus and I don't get that little square box that shows up on the buttons anymore... Solved both problems at once. :) I also tried Ezzaral's method (which i like btw) and it worked perfect as well. Plus, if focusing is important to you, this doesn't affect anything focusable in your program.. This is A+ help.... thnx guys.. +Rep points! :) |
| All times are GMT -4. The time now is 5:50 am. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC