Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (482)
Games in Android Showcase (110)
games submitted by our members
Games in WIP (550)
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  
  KeyListener probs, noo not another one  (Read 2301 times)
0 Members and 1 Guest are viewing this topic.
Offline DrWarm

Junior Newbie





« Posted 2005-10-25 07:26:02 »

Man i just cannot get this to work, could u please help!!
What am i doing wrong:
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  
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;

public class HumanPlayer extends JFrame{
   
   //
  double velocity = 0;
   double speed = 5;
   boolean upkey, downkey, leftkey, rightkey;
   
   public HumanPlayer(){
      addKeyListener(listener);
   }
   
   public double getVel(){
      if(upkey){
         velocity += speed;
      } else if(downkey){
         velocity -= speed;
      }
      velocity = velocity * .98;
     
      return velocity;
   }
   /*
   addWindowListener(new WindowAdapter(){
      public void windowClosing(WindowEvent e){
         System.exit(0);
      }
   });
   */
 
   
   KeyListener listener = new KeyListener(){
      public void keyPressed(KeyEvent e){
         int code = e.getKeyCode();
         
         switch(code){
            case KeyEvent.VK_UP: upkey = true; System.out.println("Up pressed"); break;
            case KeyEvent.VK_LEFT: leftkey = true; break;
            case KeyEvent.VK_RIGHT: rightkey = true; break;
            case KeyEvent.VK_DOWN: downkey = true; break;
         }
         
      };
     
      public void keyTyped(KeyEvent e){};
     
      public void keyReleased(KeyEvent e){
         int code = e.getKeyCode();
         
         switch(code){
            case KeyEvent.VK_UP: upkey = false; System.out.println("Up released"); break;
            case KeyEvent.VK_LEFT: leftkey = false; break;
            case KeyEvent.VK_RIGHT: rightkey = false; break;
            case KeyEvent.VK_DOWN: downkey = false; break;
         }
         
      }
   };
}
I can't get the keyListener to work, i must just be doing something wrong then?
I can give the other files if u need them. I'm just trying to get a box to move around atm.
Thanks,
        Dr Warm
Offline Sakazaki

Junior Newbie





« Reply #1 - Posted 2005-10-25 09:23:37 »

Maybe you have to call  getVel() in your keyPressed method.

In your code when you press a key  (e.g. up key) you set  upkey to true, but nobody know that happend; on release you set it to false, and again nobody "see" this change.  Wink
Offline JAW

Senior Member


Medals: 2



« Reply #2 - Posted 2005-10-25 10:29:55 »

I cannot find any errors in your KeyListener, but you should try use { } behind the case, if you use multiple commands:

case KeyEvent.VK_UP: { up = true; System.out.println("up"); break; }

you get it?

This might be why you dont get a printline

Except that, you will need a permanent loop which asks for getvel every so and then milliseconds, I suppose you have a loop somewhere and just left it out.

Just one call to getVel wont do it.

Try using the {} around your statement blocks, I cannot find anything else.
You could try to define the listener BEFORE you add it, maybe this makes trouble?

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

Senior Member


Projects: 1
Exp: 15 years


Used to be bleb


« Reply #3 - Posted 2005-10-25 10:59:56 »

I cannot find any errors in your KeyListener, but you should try use { } behind the case, if you use multiple commands

That's a matter of personal preference, the way it is now, the println will execute normally.

I can't see any glaring errors in your code either, but something to watch out for with KeyListeners is keyboard focus. Try adding a requestFocus() call in your HumanPlayer constructor.
Offline Anon666

Junior Member




aka Abuse/AbU5e/TehJumpingJawa


« Reply #4 - Posted 2005-10-25 12:10:22 »

Alarm bells started when I got to the first line of code  Roll Eyes

Quote
public class HumanPlayer extends JFrame

That is most definitely not an 'is a' relationship  Huh
Offline DrWarm

Junior Newbie





« Reply #5 - Posted 2005-10-26 02:04:58 »

Yes getVel() is called by a Game class that contains an instance of HumanPlayer, every 30 milliseconds (every redraw).

I've used this println thing before, so it should work in the switch statement.

1  
2  
3  
4  
5  
6  
Alarm bells started when I got to the first line of code  

Quote
public class HumanPlayer extends JFrame

That is most definitely not an 'is a' relationship


Um ok, i wasn't sure. But if i don't 'extends JFrame' i can't use addKeyListener anywhere!!!
Can u please explain how to get around this!!
Offline Tzan

Junior Member





« Reply #6 - Posted 2005-10-26 15:04:14 »

What Annon meant was that a "player" is not a "frame". Usually you make a new class for in game objects that hold data like velocity. What you've done here is bundle two things into one class. This isnt a big deal if you are just hacking around.

So you could make two classes like this.

SampleGame extends JFrame
HumanPlayer     

But like I said no big deal if you are just hacking.
Offline rdcarvallo

Senior Member


Projects: 5
Exp: 15 years


2D Java games forever!


« Reply #7 - Posted 2005-10-26 16:03:10 »

Also you need to add the listener to the Game Frame.
In your Game Frame  you have some instaces of your game objects (like Human Player), so when the event is received, you update your Human Player accordingly.

Some little pieces of code:
1  
2  
3  
4  
5  
class HumanPlayer{
  public void update(Event e){
    //Process the event
 }
}


1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
class GameFrame extends JFrame{
  HumanPlayer player1;
  ...  
  public GameFrame(){
     ...
      addKeyListener(new KeyListener(){
         public void keyPressed(KeyEvent ke){
           player1.update(ke);
         }
      });
      ...
  }
  ...
}

   Note that this is one way to solve your problem there are other ways to do it.

    Rafael.-
Offline DrWarm

Junior Newbie





« Reply #8 - Posted 2005-10-26 23:36:03 »

AAAAAAARrrrrrggghhhhhhhh!!!!! This has to be one of the most simple things, but i can't get it right!! I feel that i've tried everything!!

I think the problem is in the KeyListener or in the addKeyListener, but i'm not sure what!!

I've included all my source code in this post, just in one txt file, so u'll have to break it up (Sorry i wasn't sure what
the convention was). But if you have a spare 5 mins or so, could you have a peek.

Or here's my new GameFrame.java:
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  
import javax.swing.*; // For JPanel, etc.
import java.awt.*; // For Graphics, Color etc.
import java.awt.geom.*; // For Rectangle2D, etc
import java.awt.event.*;
public class GameFrame extends JPanel {
   
   // the angle generated
  double x = 300;
   double y = 300;
   
   HumanPlayer Player = new HumanPlayer();
   // and main circle
 
   // constructor
  public GameFrame(){
      requestFocus();
      addKeyListener(listener);
   }
   KeyListener listener = new KeyListener(){
      public void keyPressed(KeyEvent ke){
         System.out.println("Key is pressed");
         Player.pressedKey(ke);
      }
      public void keyTyped(KeyEvent ke){};
      public void keyReleased(KeyEvent ke){
         Player.releasedKey(ke);
      }
   };
   
   public void paintComponent(Graphics g){
     
      super.paintComponent(g);
      Graphics2D g2d = (Graphics2D)g;
     
      //
     g2d.setColor(Color.black);
     
      y = y+Player.getVel();
      Rectangle2D.Double player = new Rectangle2D.Double(x, y, 10, 30);
     
      g2d.draw(player);
   }
}
Maybe there's something inherently wrong in there i'm not picking up!

Thanks for all the quick replies
Dr Wam
Offline swpalmer

JGO Coder




Where's the Kaboom?


« Reply #9 - Posted 2005-10-27 02:22:15 »

You've got a lot of issues.  Mostly caused by bad style I suppose.  E.g. requestFocus() and setVisible() are things that you generally don't call in a constructor.  You should probably stick to the Java coding convention of starting identifier names with a lowercase letter and class names with an uppercase letter.

You've construction code scattered all over your source files, much of it outside of constructors.

You have physics/player state updates inside paintComponent, instead of in your main game loop.

You have methods named "pressedKey" and "releasedKey" in your player class, which is really a UI thing.  You really want methods to set the player's direction of acceleration - call those methods from your KeyListener if you like.

The solution to your main problem though is that an empty panel is by default not focusable.

Simply call

setFocusable(true)

in the GameFrame constructor.


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

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #10 - Posted 2005-10-27 02:29:05 »

I was just reading through and was amazed nobody had said that yet. Yes, you can either setFocusable to true in the constructor, or
1  
2  
3  
4  
    public boolean isFocusable()
    {
        return true;
    }


You can override the isFocusable method like the above. Generally, you should go with simply calling setFocusable, but sometimes when making games you don't want the main window to ever lose focus, or you want two panels to have focus. Say, for example, you have the game window on the left and scoreboard/interface on the right. Rather than have the game panel pass its key commands to the scoreboard (or a master model) or vise versa, you can trick Java into giving them both focus all the time. Or if you have Swing elements like buttons which will steal focus upon pressing this can be useful as well.

I usually use setFocusable(true) and then every time step say requestFocus() (this gives the focus to the component requesting it) so that I am not potentially messing anything up, but I have found myself twice doing the above method for whatever advantage.

Hope that works.

See my work:
OTC Software
Offline DrWarm

Junior Newbie





« Reply #11 - Posted 2005-10-27 13:22:19 »

Quote
Simply call

setFocusable(true)
Thankyou, thankyou!! I was seriously going mental over that!!! <-- i thought it would be simple

Quote
requestFocus() and setVisible() are things that you generally don't call in a constructor
Would you believe that DrawingFrame actually came from my computer science lecturer, and has been in the course notes for prob 5 years!! So if i've learnt bad programming blame those guys!

Quote
You should probably stick to the Java coding convention of starting identifier names with a lowercase letter and class names with an uppercase letter.
I thought i was pretty good with this, the only time i didn't do it was with the instance of HumanPlayer (i named it Player).

Quote
You've construction code scattered all over your source files, much of it outside of constructors.
I'm not sure what you mean by this? I can't see what i'm doing wrong, but then i was taught to do it like this, so please tell me.

Quote
You have physics/player state updates inside paintComponent, instead of in your main game loop.
I know this is wrong, but i was just doing sort of a hack-and-slash to try and get the thing to actually move. Won't happen again Cheesy

Quote
You have methods named "pressedKey" and "releasedKey" in your player class, which is really a UI thing.  You really want methods to set the player's direction of acceleration - call those methods from your KeyListener if you like.
Makes sense, I'll try to call it something different next time. The only thing was i wanted to process the KeyEvents inside the HumanPlayer class, but probably is better to do it in the game class.

@demonpants: Thanks for the info, but i'm not totally up with the focus yet, so i think i'll have to keep reading you're post to make sense of it!


Thanks every1 you've been tons of help, i'm sure i'll more problems in a day or two! Should i make a new thread if i do or not?
Offline swpalmer

JGO Coder




Where's the Kaboom?


« Reply #12 - Posted 2005-10-28 01:57:14 »

RE: construction code...

In GameFrame you have initialization of x & y, then a constructor, then initialization of the key listener.  The member variables are usually kept together, but I sometimes also make a distiction with inner classes done this way.

Put any new issues, unrelated to KeyListener, in a new thread with an appropriate subject.

Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #13 - Posted 2005-10-28 17:16:55 »

Quote
Quote
requestFocus() and setVisible() are things that you generally don't call in a constructor
Would you believe that DrawingFrame actually came from my computer science lecturer, and has been in the course notes for prob 5 years!! So if i've learnt bad programming blame those guys!

@demonpants: Thanks for the info, but i'm not totally up with the focus yet, so i think i'll have to keep reading you're post to make sense of it!


Thanks every1 you've been tons of help, i'm sure i'll more problems in a day or two! Should i make a new thread if i do or not?
I actually called setVisible(true) in most contructors for JFrames, personally. Basically I initialize everything, set the size of the window, and then make it visible. It's always worked fine for me. I don't see why you wouldn't call getFocus() in the constructor also, as long as it is after the setVisible() call. So your teacher is not necessarily teaching you bad practices, it's just another way of doing things. swpalmer probably keeps variable initialization in the constructor and window intialization elsewhere because it reduces coupling in your code. Sure, good practice, but not necessary.

Also, if you need help understanding anything I said I'll certainly explain it. And don't bother making a new post - I always check my "show new replies to your posts" link when I log in, so I'll see it.

See my work:
OTC Software
Offline swpalmer

JGO Coder




Where's the Kaboom?


« Reply #14 - Posted 2005-10-29 03:26:53 »

I actually called setVisible(true) in most contructors for JFrames, personally. Basically I initialize everything, set the size of the window, and then make it visible. It's always worked fine for me. I don't see why you wouldn't call getFocus() in the constructor also, as long as it is after the setVisible() call. So your teacher is not necessarily teaching you bad practices, it's just another way of doing things. swpalmer probably keeps variable initialization in the constructor and window intialization elsewhere because it reduces coupling in your code. Sure, good practice, but not necessary.

Also, if you need help understanding anything I said I'll certainly explain it. And don't bother making a new post - I always check my "show new replies to your posts" link when I log in, so I'll see it.

I know that calling those methods in a constructor can work.  But things like requestFocus() in particular are rather indirect for a constructor.  As you said, I like to construct the objects in the constructor - but not the entire UI.. i.e. make the object, but don't make it visible.  That way I can construct objects and save them to be made visible later, the code is more generic/reusable.  I would definately say that the profs code was using poor style.

The new posts would be for the benfit of keeping the boards organised.  Sure threads drift off-topic all the time, but there is no sense forcing threads off topic on-purpose.  Many people skip posts based on the subject.

Offline Eli Delventhal

JGO Kernel


Medals: 42
Projects: 11
Exp: 10 years


Game Engineer


« Reply #15 - Posted 2005-10-29 09:04:42 »

Hmm, that's a good point. Kepping things robust is very important. I think the only times I ever really use setVisible are in the actual main class, so it's not like it can contain a bunch of itself. But if you were dealing with multiple windows or eveer wanted more robust visibility, that's a very good point.

See my work:
OTC Software
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.

CopyableCougar4 (14 views)
2014-08-22 19:31:30

atombrot (28 views)
2014-08-19 09:29:53

Tekkerue (25 views)
2014-08-16 06:45:27

Tekkerue (23 views)
2014-08-16 06:22:17

Tekkerue (15 views)
2014-08-16 06:20:21

Tekkerue (22 views)
2014-08-16 06:12:11

Rayexar (61 views)
2014-08-11 02:49:23

BurntPizza (39 views)
2014-08-09 21:09:32

BurntPizza (31 views)
2014-08-08 02:01:56

Norakomi (37 views)
2014-08-06 19:49:38
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
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!