0

What's the method that allows you to use the JFrame without clicking on it first? I have a game, but in order to move with WASD I first need to click on the frame when the application is run. Isn't there a method that makes it so you can use it straight away without clicking first?

I have this:

Game game = new Game();
game.frame.setResizable(false);
game.frame.setTitle(Game.title);
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);

Where should I put game.frame.requestFocus();?

Sean Connolly
  • 5,692
  • 7
  • 37
  • 74
Michael Jarvis
  • 1,115
  • 3
  • 10
  • 17
  • try Sysout(game.frame.requestFocusInWindow()) , also you should requestFocusInWindow for a container like a JPanel , not for a JFrame – nachokk Jun 21 '13 at 15:41

3 Answers3

2

It is the requestFocus() method, which puts the focus on the component that called it (JFrame in this case).

Lanaru
  • 9,421
  • 7
  • 38
  • 64
  • Before you call game.frame.setVisible(true) call game.frame.requestFocus() – Lars Jun 21 '13 at 14:53
  • Didn't work :/ It's in the main method if that helps? Also, the way I've done it is added key listeners, and if W is pressed, print: true, false, false, false. If A is pressed, print: false, true, false, false etc. Therefore, if nothing is pressed, print: false, false, false, false. It's displaying full false when I press those buttons, until I click on the JFrame :/ – Michael Jarvis Jun 21 '13 at 14:59
  • Try putting requestFocus on the very last line. I believe that the component has to be visible before you can request focus. – Lanaru Jun 21 '13 at 15:01
  • That makes sense, but it didn't work :/ Maybe it's just my laptop? :P – Michael Jarvis Jun 21 '13 at 15:06
0

Sounds like your asking how to set the focus.

Have a look at: How to focus a JFrame?

Community
  • 1
  • 1
Menelaos
  • 23,508
  • 18
  • 90
  • 155
0

It is the requestFocus() method. This puts the focus on the component that called it. You may want to have a look at the following documentation: http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html

blackpanther
  • 10,998
  • 11
  • 48
  • 78