Results 1 to 3 of 3
Thread: Issues with KeyListener
- 04-19-2011, 10:17 PM #1
Member
- Join Date
- Apr 2011
- Posts
- 1
- Rep Power
- 0
Issues with KeyListener
Well, my intention was to make a simple dot move across my frame, but it seems like my keylistener isn't working. When the program is ran, nothing happens when the UP ARROW key is pressed! Any suggestions?
heres the panel code:
/**
* noComment
*/
import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class panel extends JPanel
{
private JPanel paintPanel;
private JLabel l_1 = new JLabel("");
//private JTextArea area = new JTextArea("Area.");
private int x, y;
public panel()
{
setLayout(new BorderLayout());
paintPanel = new JPanel();
myKeyListener listener = new myKeyListener();
paintPanel.addKeyListener(listener);
//----------ADD TO THE WINDOW
add(paintPanel, BorderLayout.CENTER);
setPreferredSize(new Dimension(200,300));
}
private class myKeyListener implements KeyListener
{
public void keyPressed(KeyEvent event)
{
area.setText("" + event.getKeyCode());
if (event.getKeyCode() == KeyEvent.VK_DOWN)
{
System.out.println("DOWNARROW");
x += 10;
y += 10;
repaint();
}
}
public void keyReleased(KeyEvent event){}
public void keyTyped(KeyEvent event){}
}
public void paint(Graphics g)
{
g.fillOval(x,y, 10,10);
}
}Last edited by noComment; 04-19-2011 at 10:31 PM.
-
I'm not too familiar with this but does VK_DOWN really refer to the UP arrow on the keyboard??
Java Code:if (event.getKeyCode() == KeyEvent.VK_DOWN)
- 04-20-2011, 01:58 AM #3
Senior Member
- Join Date
- Jul 2009
- Posts
- 1,158
- Rep Power
- 5
1) Use the "Code" tags when posting code so the code is readable
2) You class extends JPanel so why are you creating a second panel?
3) Custom painting is done by overriding the paintComponent() method of JPanel NOT the paint() method and you should invoke super.paintComponent(g) as the first statement
4) KeyEvents only go to the component that has focus. By default a panel is not focusable to it will not receive key events. You need to make the panel focusable.
I suggest you read the Swing tutorial on Lesson: Performing Custom Painting (The Java™ Tutorials > Creating a GUI With JFC/Swing). There are other sections of interest as well, like "How to Write a Key Listener" that might help.
Similar Threads
-
KeyListener Issues
By xael in forum New To JavaReplies: 5Last Post: 02-19-2011, 03:48 AM -
Help with keylistener?
By Kaizo in forum New To JavaReplies: 4Last Post: 12-11-2010, 12:55 AM -
keyListener not doing anything
By imorio in forum AWT / SwingReplies: 10Last Post: 08-17-2010, 10:46 PM -
KeyListener Example
By Java Tip in forum SWTReplies: 0Last Post: 07-11-2008, 04:46 PM -
how to add a KeyListener
By leonard in forum New To JavaReplies: 1Last Post: 08-06-2007, 04:44 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks