Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (107)
games submitted by our members
Games in WIP (536)
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  
  Problem with KeyListener  (Read 750 times)
0 Members and 1 Guest are viewing this topic.
Offline Gamerulf

Junior Member


Medals: 2



« Posted 2013-03-23 17:51:05 »

Im having troubles with using a KeyListener.

When running the game, the loop starts, calls the board.update() which in turn calls the kille.update().
kille.update() is reachable but it doesnt do anything because the Keylistener doesnt "work".

I googled and read about Observers, but didnt quite understand it.

Can someone please take a look at this code and tell me what im doing wrong?

This is what my program looks like atm.
(Sorry for some swedish comments and overall shitty code)

Main class and game loop(used the "Fixed Timestep" from http://www.java-gaming.org/topics/game-loops/24220/view.html)
http://pastebin.java-gaming.org/9377a0b9345

Board class, paint/update method:
http://pastebin.java-gaming.org/377ab139549

Kille class, my character, contains the KeyListener:
http://pastebin.java-gaming.org/77ab3259948

There might be some leftover code in there from testing stuff out..

- Gamerulf
Offline ClickerMonkey

JGO Coder


Medals: 20


Game Engineer


« Reply #1 - Posted 2013-03-23 17:58:22 »

You need to add the KeyListener to the JPanel (your Board class?)

1  
board.addKeyListener( character );



Offline Gamerulf

Junior Member


Medals: 2



« Reply #2 - Posted 2013-03-23 18:44:51 »

Sorry, I dont get it.

Could I do all updates in the Board class instead of calling update in other classes?

1  
2  
3  
4  
5  
6  
7  
//Board implements KeyListener
//Kille kille = new Kille();

if (e.getKeyCode() == 39)
{
kille.x += 4*interpolation;
}

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

Junior Member


Medals: 1



« Reply #3 - Posted 2013-03-23 18:57:37 »

You have create the Kille class and its a a KeyListener thats what u know.. but the game doesn't know ... so you have to tell the game that the Kille class is a keylistener so to do that you have to add this:

1  
addKeyListener(kille)


in the main class so:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
   public GameLoop()
   {
      super("SuperFinalX");
      Container cp = getContentPane();
      cp.setLayout(new BorderLayout());
      JPanel p = new JPanel();
      p.setLayout(new GridLayout(1,2));
      cp.add(board, BorderLayout.CENTER);
      cp.add(p, BorderLayout.SOUTH);
      setSize(1280, 740);
      setResizable(false);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
     
      runGameLoop();
      addKeyListener(kille)

   }


not sure But it should work...
Offline Gamerulf

Junior Member


Medals: 2



« Reply #4 - Posted 2013-03-23 19:11:12 »

Thank god!
Been struggling with this for half a day and I couldnt find anything on how the KeyListener works :/

Thanks again!

- Gamerulf
Offline joaogl

Junior Member


Medals: 1



« Reply #5 - Posted 2013-03-23 19:40:32 »

if you want there is a much easier way to make the keylistener if you want ask me ...
Offline Gamerulf

Junior Member


Medals: 2



« Reply #6 - Posted 2013-03-23 21:06:56 »

I did it the way you posted. What is the easier way?
This way seem pretty easy to me.

- Gamerulf
Offline joaogl

Junior Member


Medals: 1



« Reply #7 - Posted 2013-03-23 21:41:49 »

I didnt posted xD... I posted how to make it work how to define it not how to do the listener...

Any way I'm going to post it...

First u need to create a few variables...

1  
2  
   private boolean[] keys = new boolean[9000];
   public boolean up, down, left, right;


Then because its a key listener u have to have this methods:

1  
2  
3  
4  
5  
6  
7  
8  
        public void keyPressed(KeyEvent e) {
   }

   public void keyReleased(KeyEvent e) {
   }

   public void keyTyped(KeyEvent e) {
   }


now to make it easier lets do this:


1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
public void keyPressed(KeyEvent e) {
      keys[e.getKeyCode()] = true;
   }

   public void keyReleased(KeyEvent e) {
      keys[e.getKeyCode()] = false;
   }

   public void keyTyped(KeyEvent e) {

   }


so like this now matter what key u want it will update all the keys.. when pressed and released...

so now to make this thing work u need a tick/update method...

1  
2  
3  
4  
5  
6  
   public void tick() {
      up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W];
      down = keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S];
      left = keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A];
      right = keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D];
   }


so like this to check if the key is pressed or no u just have to do:

1  
2  
3  
if (up) {
// do something
}


and to add more keys u just have to add them to the boolean:

1  
public boolean up, down, left, right, f1;


and add it on the tick method:

1  
2  
3  
4  
5  
6  
7  
   public void tick() {
      up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W];
      down = keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S];
      left = keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A];
      right = keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D];
      f1 = keys[KeyEvent.VK_F1];
   }


Like this is much more easy to have multiple keys....
Offline tyeeeee1
« Reply #8 - Posted 2013-03-24 00:17:16 »

I'll suggest a different way to make a Key Listener than the person above as to give you an idea of more ways to make them.

KeyboardListener Class:
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  
package Core;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyboardListener
{
    public static boolean[] pressed = new boolean[128];
   
    public static boolean isKeyPressed(int x)
    {
        return pressed[x];
    }
   
    public static KeyListener listener = new KeyListener()
    {
        @Override
        public void keyPressed(KeyEvent event)
        {
            int code = event.getKeyCode();

            if(code < pressed.length)
            {
                pressed[code] = true;
            }
        }

        @Override
        public void keyReleased(KeyEvent event)
        {
           int code = event.getKeyCode();

           if(code < pressed.length)
           {
               pressed[code] = false;
           }
        }

        @Override
        public void keyTyped(KeyEvent e)
        {
        }
    };
}


The KeyboardListener class above can easily be copy-pasted into any project in need of a key listener and all you need to do to use it is check if a key is pressed.

Example:
1  
2  
3  
4  
if(KeyboardListener.isKeyPressed(KeyEvent.VK_W))
        {
           System.out.println("Blarg");
        }


The KeyboardListener class can be modified to check for key release as well but I'll leave that up to you to do if you want to use it.[/code][/code]
Offline Jimmt
« League of Dukes »

JGO Kernel


Medals: 128
Projects: 4
Exp: 3 years



« Reply #9 - Posted 2013-03-24 03:42:52 »

How does your "KeyBoardListener" provide any more functionality than the vanilla keyListener?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline joaogl

Junior Member


Medals: 1



« Reply #10 - Posted 2013-03-24 03:45:48 »

... They are the same... the diference is if its easier to work with or no....

All do the same thing.... but on yours u'll take more time to add new keys on it...
Offline tyeeeee1
« Reply #11 - Posted 2013-03-24 15:38:07 »

How does your "KeyBoardListener" provide any more functionality than the vanilla keyListener?

It doesn't, it just seems easier to work with in my opinion.
Offline Gamerulf

Junior Member


Medals: 2



« Reply #12 - Posted 2013-03-24 17:52:17 »

KeyEvent.VK_UP, is that the integer value of the "Up Arrow"-button?

And this is easier becuase:
1. Dont need to remember button values.
2. Alot less code when using many buttons.

Anything more?

- Gamerulf
Offline joaogl

Junior Member


Medals: 1



« Reply #13 - Posted 2013-03-24 17:55:24 »

Quote
KeyEvent.VK_UP, is that the integer value of the "Up Arrow"-button?

Yes it is
Offline Gamerulf

Junior Member


Medals: 2



« Reply #14 - Posted 2013-03-24 18:04:32 »

This confuse me.
1  
2  
3  
4  
    public static boolean isKeyPressed(int x)
    {
        return pressed[x];
    }


As well as the objects he's creating.
Can you create objects and write the containing methods etc. behind it within a {};?

Similar to the way you can with arrays
1  
int[] Array = {1,2,3,4};


Or is that just because he's overriding the already existing methods?

- Gamerulf
Offline tyeeeee1
« Reply #15 - Posted 2013-03-24 18:50:54 »

This confuse me.
1  
2  
3  
4  
    public static boolean isKeyPressed(int x)
    {
        return pressed[x];
    }


As well as the objects he's creating.
Can you create objects and write the containing methods etc. behind it within a {};?

Similar to the way you can with arrays
1  
int[] Array = {1,2,3,4};


Or is that just because he's overriding the already existing methods?

All that the below method does is, when called by using KeyboardListener.isKeyPressed(KeyEvent.VK_W), it will either return true or false. It just finds out if the key that you're asking it for, i nthis case of KeyboardListener.isKeyPressed(KeyEvent.VK_W) it's the W key, is pressed or not.
1  
2  
3  
4  
    public static boolean isKeyPressed(int x)
    {
        return pressed[x];
    }


I'm not sure what you're asking with "Can you create objects and write the containing methods etc. behind it within a {};?", could you elaborate?
Offline Gamerulf

Junior Member


Medals: 2



« Reply #16 - Posted 2013-03-24 19:18:12 »

Talking about this:

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  
    public static KeyListener listener = new KeyListener()
    {
        @Override
        public void keyPressed(KeyEvent event)
        {
            int code = event.getKeyCode();

            if(code < pressed.length)
            {
                pressed[code] = true;
            }
        }

        @Override
        public void keyReleased(KeyEvent event)
        {
           int code = event.getKeyCode();

           if(code < pressed.length)
           {
               pressed[code] = false;
           }
        }

        @Override
        public void keyTyped(KeyEvent e)
        {
        }
    };


Can you "override" (think it's called that) existing methods in a class by doing this? with the {}; things.
In that case, can you create new methods in a class the same way?

EDIT: There's code tags in the real code.. Dunno how to get rid of it.[/code][/code]

- Gamerulf
Offline tyeeeee1
« Reply #17 - Posted 2013-03-24 20:27:38 »

I'm not exactly sure how that works, I learned of this way to make a KeyListener from a post I read a while ago; maybe someone that's a bit more experienced than me can answer that for you.
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.

CogWheelz (15 views)
2014-07-30 21:08:39

Riven (21 views)
2014-07-29 18:09:19

Riven (14 views)
2014-07-29 18:08:52

Dwinin (12 views)
2014-07-29 10:59:34

E.R. Fleming (32 views)
2014-07-29 03:07:13

E.R. Fleming (12 views)
2014-07-29 03:06:25

pw (42 views)
2014-07-24 01:59:36

Riven (42 views)
2014-07-23 21:16:32

Riven (30 views)
2014-07-23 21:07:15

Riven (31 views)
2014-07-23 20:56:16
HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24:22
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!