Reputation:
I was showing my friend how to move a rectangle around in a JFrame, but now I can't get it to work. Am I doing something wrong? Here's my code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
@SuppressWarnings ("serial")
public class TestClass extends JComponent implements KeyListener
{
public static TestClass testClass = new TestClass();
public int x = 250;
public static void main (String[] args)
{
JFrame frame = new JFrame ("Test Frame");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize (600, 400);
frame.setResizable (false);
frame.getContentPane().setBackground (Color.WHITE);
frame.getContentPane().add (testClass);
frame.getContentPane().addKeyListener (testClass);
frame.setVisible (true);
}
public void paintComponent (Graphics graphics)
{
super.paintComponent (graphics);
graphics.setColor (Color.BLACK);
graphics.fillRect (x, 150, 100, 100);
}
public void keyPressed (KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.VK_LEFT)
{
x -= 10;
repaint();
}
if (event.getKeyCode() == KeyEvent.VK_RIGHT)
{
x += 10;
repaint();
}
}
public void keyReleased (KeyEvent event) {}
public void keyTyped (KeyEvent event) {}
}
I've done this many times before; it's simple enough. I've looked over my code a bunch, but can't see any error here. I'm probably missing something silly. Any help?
Also, I'm aware that key bindings are better and stuff. This program was simply for demonstration purposes.
Upvotes: 1
Views: 79
Reputation: 36
I tested your code and seems like its a problem with the listener assignation; add this line and you are good to go:
frame.addKeyListener(testClass);
Upvotes: 1
Reputation: 347194
It's likely an issue with the KeyListener
and the focusability of the frame's content pane.
This is why you shouldn't use KeyListener
and should use the Key Bindings API instead.
See How to Use Key Bindings for more details
Upvotes: 2