Java-Gaming.org    
Featured games (91)
games approved by the League of Dukes
Games in Showcase (580)
games submitted by our members
Games in WIP (500)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  JPanel KeyListener not responding.  (Read 2822 times)
0 Members and 1 Guest are viewing this topic.
Offline cheeseburgers

Senior Newbie





« Posted 2012-03-02 17:32:54 »

I have a class extending JPanel and implementing a KeyListener. For some reason, the KeyListener does not respond to keys being pressed or released until I hit the TAB key once. I assume that the panel doesn't have focus for some reason, which I thought setFocusable(true); and requestFocus(); would fix. What am I doing wrong?

EDIT: I placed requestFocus() in the updateGame() method and now it works. The updateGame() method is being called from an outside class that's extending JFrame (where my game loop is). Is this solution "ok", or should I make it some other way?

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
package tw;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

import javax.swing.JPanel;

/**
 * .
 */

public class GameBoard extends JPanel implements KeyListener {
   
   private Tank tank;
   
   public GameBoard() {
     
      // Setup panel
     setFocusable(true);
      requestFocus();
      setBackground(Color.WHITE);
      setDoubleBuffered(true);
      setSize(GameServer.W_WIDTH, GameServer.W_HEIGHT);

      addKeyListener(this);
      //setFocusTraversalKeysEnabled(false);
           
      // Initialize entities
     tank = new Tank(1, true, 200, 100, 1);
   }
   
   /**
    * Update game logic
    */

   public void updateGame() {
      //System.out.println("updating");
     tank.update();
   }
     
   /**
    * Draw game objects
    */

   public void paintComponent(Graphics g) {
      super.paintComponent(g);
     
      //System.out.println("drawing");
     tank.draw(g);
           
      Toolkit.getDefaultToolkit().sync();
      g.dispose();
   }
   
   
   // Handling key input
  /////////////////////////////////////////////
  /**
    * Key input - when key is pressed.
    */

   public void keyPressed(KeyEvent e) {
      System.out.println("KEY PRESSED!");
      tank.keyPressed(e);      
   }
   
   /**
    * Key input - when key is released.
    */

   public void keyReleased(KeyEvent e) {
      System.out.println("KEY RELEASED!");
      tank.keyReleased(e);        
   }
   
   public void keyTyped(KeyEvent e) {
      // do nothing
  }

}
Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 12


Game Engineer


« Reply #1 - Posted 2012-03-02 23:47:08 »

Generally you want to avoid requesting focus repeatedly in a game loop. It causes the user to have a terrible user experience if they try to click anywhere different for focus, and it also performs differently on different OSes (Mac and PC).

Instead you should figure out who is stealing your focus and fix that. Or you can use something like JInput which doesn't need focus to work.

See my work:
OTC Software
Offline UprightPath
« Reply #2 - Posted 2012-03-02 23:51:39 »

Ugh. I support Eli's statement.

Focus is one of the most frustrating systems I have ever come across in Gui programming. Especially with Swing's. Ugh. Ugh. Double and triple ugh.

Instead of requesting focus like that (Which as Eli said will cause lots of fun system dependent), it also causes a spam of FocusGained and FocusLost events that will flood your system if anything else had focus. Especially since there is stuff like temporary focus loss (Through JOption Panes/window changes) and other such fun. If you can avoid having to deal with it in general, you should.

JInput works fairly well from what I've see. It's simple, rather intuitive. The only difference is that it's a Polling system, rather than an Listener system, which may/may-not work for what you need. If I'm wrong about that, please do correct me.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline cheeseburgers

Senior Newbie





« Reply #3 - Posted 2012-03-03 00:13:56 »

Hehe, had a feeling that was a bad idea. Anyhow, I solved it by not requesting focus in the GameBoard constructor but rather in the class that adds the GameBoard:

1  
2  
3  
gameBoard = new GameBoard();
add(gameBoard);
gameBoard.requestFocusInWindow();


Now it seems to work the way it should!
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #4 - Posted 2012-03-03 03:06:03 »

Generally you should avoid extending JPanel at all, rather you should extend JComponent if you really need Swing.

Preferrably, it is best to use a Canvas + BufferStrategy.

Offline cheekymonk3y

Senior Newbie





« Reply #5 - Posted 2012-03-03 16:58:47 »

Show us your JFrame class. I had the exact same problem today and I ended up fixing it by messing with the way things were ordered in there.

Also, I don't think you need requestFocus() at all if you fix the underlying problem, setFocusable(true) should be enough.

Offline evilfrenchguy

Junior Member


Medals: 3



« Reply #6 - Posted 2012-03-03 22:35:46 »

@ra4king

Could you kinda briefly explain what the canvas/buffer strategy is?
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #7 - Posted 2012-03-03 23:59:32 »

The last paragraph and the code should explain it Smiley

Offline evilfrenchguy

Junior Member


Medals: 3



« Reply #8 - Posted 2012-03-04 16:54:23 »

I see. That seems pretty cool.

What's the point to having the double do-while loops though?

If I'm understanding this right, the pseudo-code for the loop would be something like:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
As long as I'm running...
         update the game logic.

         I will...
                     I will...
                                  Borrow the buffer'
s graphics object.

                                  Do my drawing with it.

                                  Toss it, I'm done drawing.
                     If there is still things that need to be drawn on the buffer, I'
ll do it again.
         If the buffer's been flipped and drawn, I'll do it again.

         Take a nap.


I'm not seeing the need for 2 do-while loops for drawing....Oh....wait. Double buffering.....right...

So, what exactly does contentsRestored() and contentsLost() check for? The javadoc doesn't explain it well.
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #9 - Posted 2012-03-04 21:28:06 »

The JavaDocs says to read VolatileImage's JavaDoc for a discussion on lost and restored buffers.

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

xsi3rr4x (50 views)
2014-04-15 18:08:23

BurntPizza (46 views)
2014-04-15 03:46:01

UprightPath (62 views)
2014-04-14 17:39:50

UprightPath (44 views)
2014-04-14 17:35:47

Porlus (61 views)
2014-04-14 15:48:38

tom_mai78101 (84 views)
2014-04-10 04:04:31

BurntPizza (142 views)
2014-04-08 23:06:04

tom_mai78101 (242 views)
2014-04-05 13:34:39

trollwarrior1 (201 views)
2014-04-04 12:06:45

CJLetsGame (208 views)
2014-04-01 02:16:10
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!