Results 1 to 18 of 18
Thread: Key Listeners
- 09-17-2011, 12:15 AM #1
Member
- Join Date
- Jul 2011
- Posts
- 38
- Rep Power
- 0
Key Listeners
I have been trying to design a simple key listener that listens to the enter key. here is my code;
I cannot understand why it will not workJava Code:import javax.swing.*; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class pacman extends JFrame{ public pacman() { super(); setSize(500, 500); mypanel second = new mypanel(); second.setFocusable(true); add(second); setVisible(true); setDefaultCloseOperation(3); validate(); } public static void main(String args[]) { pacman pac = new pacman(); } public class mypanel extends JPanel { public int x; public int y; public mypanel() { super(); addKeyListener(new KeyAdapter(){ public void pressedkey(KeyEvent e) { System.out.println("Here"); if (e.getKeyCode()==KeyEvent.VK_UP) { y++; } else if (e.getKeyCode()==KeyEvent.VK_DOWN) { y--; } else if (e.getKeyCode()==KeyEvent.VK_RIGHT) { x++; } else if (e.getKeyCode()==KeyEvent.VK_LEFT) { x--; } repaint(); } }); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.yellow); x = this.getSize().width/2-15; y = this.getSize().height/2-15; g.fillOval(x, y, 30, 30); g.setColor(Color.black); this.setOpaque(true); this.setBackground(Color.black); } } }
I don't know whether i need to learn about key binding and setting the focus of the component
-
Re: Key Listeners
What API is pressedkey from? You can't make stuff up and expect it to work.
And yes, you should look into learning how to use key bindings.
Also: don't hard-code your x and y in the paintComponent method. What good will changing their values in your program if it's only going to be reset back to hard coded values whenever the component is painted?
Also: don't set background or opaque from within paintComponent. These should be set once in the constructor.Last edited by Fubarable; 09-17-2011 at 12:27 AM.
- 09-17-2011, 12:37 AM #3
Member
- Join Date
- Jul 2011
- Posts
- 38
- Rep Power
- 0
Re: Key Listeners
what did i make up? and what do i need to add to make it work
- 09-17-2011, 01:18 AM #4
Member
- Join Date
- Jul 2011
- Posts
- 38
- Rep Power
- 0
Re: Key Listeners
I still don't understand why the program won't run even after i set the focus to my panel.
- 09-17-2011, 01:26 AM #5
Moderator
- Join Date
- Jul 2010
- Location
- California
- Posts
- 1,604
- Rep Power
- 5
Re: Key Listeners
Read the API for KeyListener: pressedkey != keyPressed. For future reference, using the @Override annotation would have given you a compile time error and caught this error much earlier. And yes, look into using KeyBindings. Lastly, I recommend you take some time to read about java code conventions
-
Re: Key Listeners
Exactly, pressedkey doesn't exist. It may sound right, but since it was made up, it overrides no super method and the JVM won't respond to it as it would to a proper method override. To use these things you must use the references available including the API and the tutorials. That's what they're for.
- 09-17-2011, 01:37 AM #7
Member
- Join Date
- Jul 2011
- Posts
- 38
- Rep Power
- 0
Re: Key Listeners
isn't pressed key a method in the interface KeyListener?
-
Re: Key Listeners
- 09-17-2011, 01:43 AM #9
Member
- Join Date
- Jul 2011
- Posts
- 38
- Rep Power
- 0
Re: Key Listeners
now the key pressed method works but the if e.getKeyCode == VK_UP or for any other arrow key won't work
- 09-17-2011, 02:27 AM #10
Senior Member
- Join Date
- Apr 2010
- Location
- Philippines
- Posts
- 580
- Rep Power
- 4
Re: Key Listeners
As suggested above, use Key Binding.
How to Use Key Bindings (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)
- 09-17-2011, 05:13 AM #11
Senior Member
- Join Date
- Jul 2009
- Posts
- 1,143
- Rep Power
- 5
Re: Key Listeners
> or for any other arrow key won't work
Define won't work. What do you expect to happen?
- 09-17-2011, 07:11 AM #12
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,372
- Blog Entries
- 7
- Rep Power
- 17
- 09-17-2011, 03:43 PM #13
Member
- Join Date
- Jul 2011
- Posts
- 38
- Rep Power
- 0
Re: Key Listeners
I read the key binding tutorial and it makes sense to me except for one thing.
I don't understand how to attach the "SPACE" string to the actual space key. I wouldn't know how to replace the space keystroke with any of the arrow keys in the code. Lastly, I don't know how to have the actions performed when a key is pressed or when its released.component.getInputMap().put(KeyStroke.getKeyStroke ("SPACE"),
"pressed");
component.getInputMap().put(KeyStroke.getKeyStroke ("released SPACE"),
"released");
component.getActionMap().put("pressed",
pressedAction);
component.getActionMap().put("released",
releasedAction);
//where pressedAction and releasedAction are javax.swing.Action objectsLast edited by wired-in=p; 09-17-2011 at 04:06 PM.
-
Re: Key Listeners
There are several ways of getting the KeyStroke for key binding. Myself, I like to use KeyStroke.getKeyStroke(int, int), the first int is obtained by using the vk_ constants held by the KeyEvent class. For instance, assuming your code has a String constant for up:
Java Code:private static final String UP = "UP";
Then you could do one key binding like so:
Java Code:int condition = JComponent.WHEN_IN_FOCUSED_WINDOW; InputMap inputMap = getInputMap(condition); ActionMap actionMap = getActionMap(); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), UP); actionMap.put(UP, new AbstractAction() { public void actionPerformed(ActionEvent arg0) { y--; repaint(); } });
For example:
Edit: to get released vs pressed, look at the KeyStroke API for the appropriate method. Myself I'd use the getKeyStroke(int, int, boolean) for this.Java Code:import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.*; @SuppressWarnings("serial") public class MoveBall extends JPanel { private static final String UP = "UP"; private static final String DOWN = "DOWN"; private static final String LEFT = "LEFT"; private static final String RIGHT = "RIGHT"; private static final Color BACKGROUND = Color.black; private static final Color BALL_COLOR = Color.yellow; private static final int BALL_WIDTH = 30; private static final int PREF_WIDTH = 500; private static final int PREF_HEIGHT = PREF_WIDTH; private static final Dimension PREF_SIZE = new Dimension(PREF_WIDTH, PREF_HEIGHT); private int x = PREF_WIDTH / 2; private int y = PREF_HEIGHT / 2; public MoveBall() { setBackground(BACKGROUND); int condition = JComponent.WHEN_IN_FOCUSED_WINDOW; InputMap inputMap = getInputMap(condition); ActionMap actionMap = getActionMap(); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), UP); actionMap.put(UP, new AbstractAction() { public void actionPerformed(ActionEvent arg0) { y--; repaint(); } }); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), DOWN); actionMap.put(DOWN, new AbstractAction() { public void actionPerformed(ActionEvent arg0) { y++; repaint(); } }); // etc for left and right } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(BALL_COLOR); g2.fillOval(x - BALL_WIDTH / 2, y - BALL_WIDTH / 2, BALL_WIDTH, BALL_WIDTH); } @Override public Dimension getPreferredSize() { return PREF_SIZE; } private static void createAndShowGui() { JFrame frame = new JFrame("Move Ball"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new MoveBall()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } }Last edited by Fubarable; 09-17-2011 at 04:19 PM.
- 09-17-2011, 04:18 PM #15
Member
- Join Date
- Jul 2011
- Posts
- 38
- Rep Power
- 0
Re: Key Listeners
Thank you very much. One question, what is the 0 argument in KeyStroke.getKeyStroke for?
-
- 09-17-2011, 04:27 PM #17
Member
- Join Date
- Jul 2011
- Posts
- 38
- Rep Power
- 0
Re: Key Listeners
Thanks again, my program now works. however, i made the ball move one pixel when i press an arrow key. it was moving too slow so i changed it to 10 pixels, which is a better speed but it seems like it is jumping around. is there anyway i can lower the time it takes to press a key so the ball moves smoother?
-
Re: Key Listeners
Consider using a Timer for your game loop. You could have a right-arrow key-down change a moveRight boolean to true and key-up change it to false and the game loop would move the sprite to the right if (moveRight).
Similar Threads
-
two different Listeners
By Billaguana in forum New To JavaReplies: 8Last Post: 01-21-2011, 03:20 AM -
key listeners
By zjames in forum New To JavaReplies: 22Last Post: 11-24-2010, 05:58 AM -
Can't implement listeners
By xael in forum New To JavaReplies: 3Last Post: 09-02-2010, 06:33 PM -
Help with Listeners
By Psyclone in forum AWT / SwingReplies: 8Last Post: 02-09-2010, 07:21 PM -
Seriously need help on my listeners!!
By themburu in forum Java AppletsReplies: 4Last Post: 05-26-2008, 10:41 AM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks