Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (497)
Games in Android Showcase (114)
games submitted by our members
Games in WIP (563)
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  
  What's wrong with my KeyListener?  (Read 792 times)
0 Members and 1 Guest are viewing this topic.
Offline Neil Q

Junior Newbie





« Posted 2013-02-14 10:42:17 »

I'm trying to get a simple rectangle moving around on my JPanel.

everything is set up except for the fact the rectangle doesn't respond to the keys.

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  
package game;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.*;

@SuppressWarnings("serial")
public class Main extends JPanel implements KeyListener, ActionListener {
   
   private final int frameHeight = 400;
   private final int frameWidth = 400;
   private int objectDimension = 15;
   
   JMenuBar menuBar;
   JMenu file;
   JMenuItem newGame;
   JMenuItem checkScore;
   JMenuItem endGame;
   
   int objectX = 150;
   int objectY = 150;
   
   int velX = 0; // speed object moves X axis
  int velY = 0; // speed object moves Y axis
 
   // CONSTRUCTOR
  public Main() {
     
      //JMenuBar
     menuBar = new JMenuBar();
      file = new JMenu("File");
      newGame = new JMenuItem("New Game");
      checkScore = new JMenuItem("Check Score");
      endGame = new JMenuItem("End Game");
     
      menuBar.add(file);
      file.add(newGame);
      file.add(checkScore);
      file.addSeparator();
      file.add(endGame);
     
     
      addKeyListener(this);
      setFocusable(true);
      setFocusTraversalKeysEnabled(false);
   }
     
   public JMenuBar setJMenuBar(){
      return menuBar;
   }
   
   // SETS SIZE FOR FRAME
     @Override
      public Dimension getPreferredSize() {
         return new Dimension(frameWidth, frameHeight);
      }
   
   //PAINTCOMPONENT  
  public void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.fillRect(objectX, objectY, objectDimension, objectDimension);
     
     
   }
   
   public void actionPerformed(ActionEvent e){
      objectX = objectX + velX;
      objectY = objectY + velY;
     
      repaint();
   }
   
   public void keyPressed(KeyEvent e){
      int key = e.getKeyCode();
     
      if(key == KeyEvent.VK_LEFT){
         velX = -1;
         velY = 0;
      }
      if(key == KeyEvent.VK_UP){
         velY = -1;
         velX = 0;
      }
      if(key == KeyEvent.VK_RIGHT){
         velX = +1;
         velY = 0;
      }
      if(key == KeyEvent.VK_DOWN){
         velY = +1;
         velX = 0;
      }
   }
   
   public void keyReleased(KeyEvent e){}
   public void keyTyped(KeyEvent e){}
         
   
   
   public static void createAndShowGui() {
      Main main = new Main();
     
      JFrame frame = new JFrame("My New Game!");
      frame.getContentPane().add(main);
      frame.setJMenuBar(main.setJMenuBar());
      frame.pack();
      frame.setVisible(true);
     
   }
   
   // MAIN METHOD
  public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable(){
         public void run(){
            createAndShowGui();
         }
      });  
   }
   
}


any suggestions of where I'm going wrong?
Offline jonjava
« Reply #1 - Posted 2013-02-14 11:39:06 »

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
 menuBar = new JMenuBar();
      file = new JMenu("File");
      newGame = new JMenuItem("New Game");
      checkScore = new JMenuItem("Check Score");
      endGame = new JMenuItem("End Game");
     
      menuBar.add(file);
      file.add(newGame);
      file.add(checkScore);
      file.addSeparator();
      file.add(endGame);
     
      this.add(menuBar); // Try this?
     
      addKeyListener(this);
      setFocusable(true);
      setFocusTraversalKeysEnabled(false);
   }

Offline StrideColossus
« Reply #2 - Posted 2013-02-14 11:45:19 »

I don't think it's a problem with your key listener, the action listener is the problem - it will never get invoked as far as I can tell since none of the components are generating events that will update the position and repaint the component.

Either move the update/repaint code into your key handler or add some component that will generate an ActionEvent, i.e. a button or your menu.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Neil Q

Junior Newbie





« Reply #3 - Posted 2013-02-14 15:41:43 »

hi StrideColossus,
you were right about it being the ActionListener.
I added the repaint to the keyhandler with still nothing happening.

but I added commands for my JMenuBar and the rectangle responds when I click something in the JMenuBar.

I'm confused about what I can use in the actionPerformed that will update everything I press one of the assigned keys..

Any suggestion?
Offline StrideColossus
« Reply #4 - Posted 2013-02-14 15:52:07 »

Any suggestion?

I'm afraid you're pushing the limits of my meagre AWT/SWING knowledge - I'm surprised what you tried didn't work, anybody else shed any light?
Offline deepthought
« Reply #5 - Posted 2013-02-14 16:25:26 »

1. your actionlistener hasn't been added to anything (timer, button, etc.)
2. how do you want motion to work? it it's current state, your square will keep going whichever direction was last pressed.

put
1  
2  
 Timer t = new Timer(100, this);
      t.start();

at the end of your constructor

jocks rule the highschools. GEEKS RULE THE WORLD MWAHAHAHA!!
captain failure test game
Offline Neil Q

Junior Newbie





« Reply #6 - Posted 2013-02-14 16:47:47 »

Deepthought, that worked perfectly.
Could I get a quick explanation on exactly what its doing?

I will add the keyReleased commands to set everything back to 0
Offline deepthought
« Reply #7 - Posted 2013-02-14 18:05:09 »

your main class implemented an Actionlistener, which would have worked. However, you did not add it to anything that can call actionperformed.

the timer class takes a constructor Timer(delay,actionlistener);
start() starts the timer.
you can use different values in delay for different framerates.


I would recommend a different approach besides swing/java2d for games, but if you've just started learning, it's as good a place to start as any.

jocks rule the highschools. GEEKS RULE THE WORLD MWAHAHAHA!!
captain failure test game
Offline Neil Q

Junior Newbie





« Reply #8 - Posted 2013-02-14 19:30:48 »

Thanks for the help.
I'm just starting, but if there's a better way to go about it, I'd prefer to start off that way?
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.

BurntPizza (18 views)
2014-09-19 03:14:18

Dwinin (34 views)
2014-09-12 09:08:26

Norakomi (62 views)
2014-09-10 13:57:51

TehJavaDev (84 views)
2014-09-10 06:39:09

Tekkerue (42 views)
2014-09-09 02:24:56

mitcheeb (64 views)
2014-09-08 06:06:29

BurntPizza (47 views)
2014-09-07 01:13:42

Longarmx (35 views)
2014-09-07 01:12:14

Longarmx (39 views)
2014-09-07 01:11:22

Longarmx (36 views)
2014-09-07 01:10:19
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!