Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (476)
Games in Android Showcase (106)
games submitted by our members
Games in WIP (532)
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  
  De-activating a key-listener  (Read 1521 times)
0 Members and 1 Guest are viewing this topic.
Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Posted 2011-12-21 23:08:24 »

I am making keyboard input-based menus for a game and can't figure out how to deactivate a keylistener after I'm done using it.

Also, i am trying to make it so that when I press tab while playing, it brings me back to the menu. I tried calling my menuInit method when tab is pressed, but nothing happens.

Here's my code -

Main 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  
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  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
package main;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

public class Main extends Canvas implements Runnable
{
   private static final long serialVersionUID = 1L;
   
   public static final int WIDTH = 160;
   public static final int HEIGHT = 120;
   public static final int SCALE = 3;
   
   public int TITLE_FONT_SIZE = 15;
   
   public boolean running = false;
   public boolean mainMenu = false;
   
   public boolean startGame = false;
   public boolean startMenu = true;
   
   public int ticks = 0;
   public int frames = 0;
   public int fps = 0;
   private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
   long lastTimer1 = System.currentTimeMillis();
   long startingTime = lastTimer1;
   long score;

   
   Player p;
   
   public void start()
   {
      menuInit();
      new Thread(this).start();
   }
   
   public void stop()
   {
      running = false;
   }
   
   public void gameInit()
   {
      p = new Player();
      addKeyListener(new ALGame());
      setFocusable(true);
      mainMenu = false;
      running = true;
   }
   
   public void menuInit()
   {
      running = false;
      addKeyListener(new ALMenu());
      mainMenu = true;
   }
   
   public void run()
   {
      long lastTime = System.nanoTime();
      double unprocessed = 0;
      double nsPerTick = 1000000000.0 / 60.0;
     
      while (mainMenu)
      {
         render();
      }
     
      while (running)
      {
         long now = System.nanoTime();
         unprocessed += (now - lastTime) / nsPerTick;
         lastTime = now;
         boolean shouldRender = true;
         
         while (unprocessed >= .2)
         {
            tick();
            unprocessed -= .2;
            shouldRender = true;
         }
         
         Thread.yield();
         
         if (shouldRender)
         {
            frames++;
            render();
         }
         
         if (System.currentTimeMillis() - lastTimer1 > 1000)
         {
            lastTimer1 += 1000;
            System.out.println(ticks + " ticks, " + fps + " fps");
            fps = frames;
            frames = 0;
            ticks = 0;
         }
      }
   }
   
   public void tick()
   {      
      p.move();  
     
      ticks++;
   }
   
   public void render()
   {
      BufferStrategy bs = getBufferStrategy();
     
      if (bs == null)
      {
         this.createBufferStrategy(3);
         return;
      }
     
      Graphics g = image.getGraphics();
      Graphics2D g2d = (Graphics2D) g;
     
      super.paint(g);
     
      if (mainMenu)
      {
         g2d.setColor(Color.WHITE);        
         g2d.setFont(new Font("Times New Roman", 5, TITLE_FONT_SIZE));
         g2d.drawString("Play (space)", WIDTH / 2 - 45, HEIGHT / 2 - 10);
         g2d.drawString("Quit (esc)", WIDTH / 2 - 45, HEIGHT / 2 + 10);
      }
     
      if (running)
      {            
         g.fillRect(10, 10, WIDTH - 20, HEIGHT - 20);
         g2d.drawImage(p.getImage(), p.getX(), p.getY(), null);
     
         g2d.setFont(new Font("Arial", 5, 10));
         g2d.drawString(fps + "fps", 1, 9);
      }
     
      g.dispose();
     
      g = bs.getDrawGraphics();
      g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
      g.dispose();
      bs.show();
   }
   
   public static void main(String[] args)
   {
      Main game = new Main();
      game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
      game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
      game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
     
      JFrame frame = new JFrame("Untitled");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLayout(new BorderLayout());
      frame.add(game);
      frame.pack();
      frame.setResizable(false);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
      game.start();
   }
   
   private class ALGame extends KeyAdapter
   {
      public void keyReleased(KeyEvent e)
      {
         p.keyReleased(e);
      }
     
      public void keyPressed(KeyEvent e)
      {
         p.keyPressed(e);
      }
   }
   
   private class ALMenu extends KeyAdapter
   {
      public void keyReleased(KeyEvent e)
      {
         int key = e.getKeyCode();
         if (key == KeyEvent.VK_SPACE) gameInit();
         if (key == KeyEvent.VK_ESCAPE) System.exit(0);
      }
   }
   
   public void getScore()
   {
      long currentTime = System.currentTimeMillis();
      score = (currentTime - startingTime) / 100;
   }
}


Player 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  
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  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
package main;

import java.awt.Image;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;

public class Player
{
   double negChange = -.2;
   double posChange = .2;
   
   double x, dx, y, dy, xSpeed, ySpeed;
   Image player;
   
   Main m;
   
   int key2;
   boolean move = false;
   
   ImageIcon up = new ImageIcon(getClass().getResource("/textures/Up.png"));
   ImageIcon down = new ImageIcon(getClass().getResource("/textures/Down.png"));
   ImageIcon leftRunning = new ImageIcon(getClass().getResource("/textures/LeftRunning.png"));
   ImageIcon rightRunning = new ImageIcon(getClass().getResource("/textures/RightRunning.png"));
   
   public Player()
   {
      m = new Main();
      player = down.getImage();
      x = 12;
      y = 12;
   }
   
   public void move()
   {
      if (x <= 1)
      {
         if (dx > 0)
         {
            move = true;
         }
         
         else
         {
            dx = 0;
            move = false;
         }
      }
     
      else if (x >= 145)
      {
         if (dx < 0)
         {
            move = true;
         }
         
         else
         {
            dx = 0;
            move = false;
         }
      }
     
      else if (y <= 1)
      {
         if (dy > 0)
         {
            move = true;
         }
         
         else
         {
            dx = 0;
            move = false;
         }
      }
     
      else if (y >= 105)
      {
         if (dy < 0)
         {
            move = true;
         }
         
         else
         {
            dx = 0;
            move = false;
         }
      }
     
      else move = true;
     
      if (move)
      {
         x = x + dx;
         y = y + dy;
      }
   }
   
   public int getX()
   {
      return (int) x;
   }
   
   public int getY()
   {
      return (int) y;
   }
   
   public Image getImage()
   {
      return player;
   }
   
   public void keyPressed(KeyEvent e)
   {
      int key = e.getKeyCode();
     
      if (key == KeyEvent.VK_A)
      {
         if ((key2 != 2) && (key2 != 3) && (key2 != 4))
         {
            key2 = 1;
            dx = negChange;
            player = leftRunning.getImage();
         }
      }
      if (key == KeyEvent.VK_D)
      {
         if ((key2 != 1) && (key2 != 3) && (key2 != 4))
         {
            key2 = 2;
            dx = posChange;
            player = rightRunning.getImage();
         }
      }  
      if (key == KeyEvent.VK_W)
      {
         if ((key2 != 1) && (key2 != 2) && (key2 != 4))
         {
            key2 = 3;
            dy = negChange;
            player = up.getImage();
         }
      }
      if (key == KeyEvent.VK_S)
      {
         if ((key2 != 1) && (key2 != 2) && (key2 != 3))
         {
            key2 = 4;
            dy = posChange;
            player = down.getImage();
         }
      }
      if (key == KeyEvent.VK_TAB) m.menuInit();
   }
   
   public void keyReleased(KeyEvent e)
   {
      int key = e.getKeyCode();
     
      if (key == KeyEvent.VK_A)
      {
         dx = 0;
         key2 = 0;
      }
      if (key == KeyEvent.VK_D)
      {
         dx = 0;
         key2 = 0;
      }
      if (key == KeyEvent.VK_W)
      {
         dy = 0;
         key2 = 0;
      }
      if (key == KeyEvent.VK_S)
      {
         dy = 0;
         key2 = 0;
      }
   }
}


Thanks.

Check out my website!
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #1 - Posted 2011-12-21 23:53:52 »

removeKeyListener(myListener);

Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #2 - Posted 2011-12-22 00:09:15 »

removeKeyListener(myListener);

When I call this line -
1  
addKeyListener(new ALMenu());


this line here -
1  
removeKeyListener(ALMenu);


Doesn't even recognize ALMenu. Should I be putting something else as the parameter?

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

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #3 - Posted 2011-12-22 00:11:46 »

No you should be storing the reference to ALMenu like so:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
public class Main ... {
    ...
    ALMenu alMenu = new AlMenu();
   
    public void menuInit() {
        addKeyListener(alMenu);
        ...
    }
   
    public void gameInit() {
        removeKeyListener(alMenu);
        ...
    }
   
    ...
}

Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #4 - Posted 2011-12-22 00:15:02 »

Thanks!

Also, I am trying to make it so that when I press tab while playing, it brings me back to the menu. I tried calling my menuInit method when tab is pressed, but nothing happens.

^^See code above

Check out my website!
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #5 - Posted 2011-12-22 00:16:25 »

O_o You are creating a completely separate instance of Main inside your player class. Shouldn't you be passing the Main instance to the player?

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
public class Main {
    private Player player;
    public Main() {
        player = new Player(this):
    }
}

public class Player {
    private Main main;
   
    public Player(Main main) {
        this.main = main;
    }
}

Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #6 - Posted 2011-12-22 00:36:08 »

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
public class Main {
    private Player player;
    public Main() {
        player = new Player(this):
    }
}

public class Player {
    private Main main;
   
    public Player(Main main) {
        this.main = main;
    }
}


I have the same thing here

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
public Main()
   {
      p = new Player(this);
   }

public Player(Main main)
   {
      this.main = new Main();
      player = down.getImage();
      x = 12;
      y = 12;
   }


but it now gives a stackOverFlowError when I run. Cry

Check out my website!
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #7 - Posted 2011-12-22 00:48:30 »

No! You are creating a new Main object! You are supposed to assign main to this.main.

You need to read up more on objects, methods, and variables before you do graphics.

Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #8 - Posted 2011-12-22 01:22:03 »

Oops. Sorry.

This (I think) brought me one step closed to figuring out why I can't re-open the menu. When escape is pressed while in game now, it closes the window. I put a println where it's calls Main.menuInit(); and it print just fine, so it's getting to that point, it just isn't doing what I want to, which is:

A: Program opened, menuInit started
B: In menuInit, mainMenu is set to true, running is set to false, keylistener alGame is removed, and keylistener alMenu is added
C: In game loop now,
1  
2  
3  
4  
while (mainMenu)
      {
         render();
      }

D:When in the menu, if space is pressed, gameInit is called, new Player is created (p = new Player(this)Wink, alMenu is removed, alGame is added, mainMenu is set to false, and running is set to true

This all works just fine.

E: When escape is pressed in game, main.menuInit is called, which prints "WORKING" to the console, sets mainMenu to true and running to false which SHOULD initiate the while (running) in the game loop, but instead, decides to close.

Shocked

Check out my website!
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #9 - Posted 2011-12-22 01:36:34 »

If it sets running to false, why would the while(running) loop run? Tongue

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

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #10 - Posted 2011-12-22 01:38:31 »

If it sets running to false, why would the while(running) loop run? Tongue

My bad, I meant "sets mainMenu to true and running to false which SHOULD initiate the while (mainMenu) in the game loop, but instead, decides to close."

Check out my website!
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #11 - Posted 2011-12-22 01:45:19 »

That's because the run() method returns....

Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #12 - Posted 2011-12-22 01:47:22 »

That's because the run() method returns....

*tries to understand what that means..fails

What does that mean?

p.s. Thanks so much for the help, I'm obviously still learning :x

Check out my website!
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #13 - Posted 2011-12-22 01:52:02 »

You see the run() method that contains both while loops?
Well when you set running to false, the while(running) loop ends, then execution reaches the end of the run() method and the thread ends.

Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #14 - Posted 2011-12-22 01:58:21 »

OH!

Thanks! Cheesy

And of course, something doesn't work D:

I simply changed the "running" boolean to "playing" and added a new "running" boolean that is always true until you exit.

However, when I press escape, it flashes to the menu then closes again.

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  
while (running)
      {
         while (mainMenu)
         {
            render();
         }
     
         while (playing)
         {
            long now = System.nanoTime();
            unprocessed += (now - lastTime) / nsPerTick;
            lastTime = now;
            boolean shouldRender = true;
         
            while (unprocessed >= .2)
            {
               tick();
               unprocessed -= .2;
               shouldRender = true;
            }
         
            Thread.yield();
         
            if (shouldRender)
            {
               frames++;
               render();
            }
         
            if (System.currentTimeMillis() - lastTimer1 > 1000)
            {
               lastTimer1 += 1000;
               System.out.println(ticks + " ticks, " + fps + " fps");
               fps = frames;
               frames = 0;
               ticks = 0;
            }
         }
      }

Check out my website!
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #15 - Posted 2011-12-22 01:59:19 »

Make sure you don't set running to false accidentally anywhere. Otherwise, try debugging it.

Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #16 - Posted 2011-12-22 02:11:36 »

Finally fixed it.

Thanks so much! +1 to you good sir

Check out my website!
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #17 - Posted 2011-12-22 02:22:02 »

Glad to help Cheesy

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.

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

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

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

Riven (15 views)
2014-07-23 20:56:16

ctomni231 (43 views)
2014-07-18 06:55:21

Zero Volt (40 views)
2014-07-17 23:47:54

danieldean (32 views)
2014-07-17 23:41:23

MustardPeter (36 views)
2014-07-16 23:30:00

Cero (51 views)
2014-07-16 00:42:17

Riven (50 views)
2014-07-14 18:02:53
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!