How to use KeyListener with JFrame?
So, I was trying to make a rectangle move with a KeyEvent
(KeyListener
) and whenever I try to hit the key, the rectangle doesn't move.
The rectangle is drawn, but whenever I hit the left
and right
keys, nothing happens.
I have two classes, one is my main class with the keyEvents and the frame and the other, draws the rectangle and holds the function to move the rectangle.
Here is my code:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class mainFrame extends JFrame implements KeyListener{
mainDraw Draw = new mainDraw();
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_D){
Draw.moveRight();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {}
public mainFrame()
{
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public static void main(String[] args) {
mainFrame M1 = new mainFrame();
mainDraw Draw = new mainDraw();
JFrame frame = new JFrame("Square Move Practice");
//frame
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(Draw);
}
}
And now the second class:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
public class mainDraw extends JComponent{
public int x = 50;
public int y = 50;
public void paint(Graphics g){
g.drawRect(x, y, 50, 50);
g.fillRect(x, y, 50, 50);
g.setColor(Color.BLACK);
}
public void moveRight()
{
x = x + 5;
y = y + 0;
repaint();
}
}
Please tell me how I can move the rectangle. Thanks in advance!
Solution 1:
The rectangle is not moving because you are not using JFrame
correctly. You have to assign frame
to new mainFrame()
instead of ignoring the instantiated mainFrame
object.
There are several other issues as @MadProgrammer points out.
Here is the code that fixes some of the issues:
mainFrame.java
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class mainFrame extends JFrame implements KeyListener{
private mainDraw draw;
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed");
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_RIGHT)
draw.moveRight();
else if(e.getKeyCode()== KeyEvent.VK_LEFT)
draw.moveLeft();
else if(e.getKeyCode()== KeyEvent.VK_DOWN)
draw.moveDown();
else if(e.getKeyCode()== KeyEvent.VK_UP)
draw.moveUp();
}
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped");
}
public mainFrame(){
this.draw=new mainDraw();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
mainFrame frame = new mainFrame();
frame.setTitle("Square Move Practice");
frame.setResizable(false);
frame.setSize(600, 600);
frame.setMinimumSize(new Dimension(600, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(frame.draw);
frame.pack();
frame.setVisible(true);
}
});
}
}
mainDraw.java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
public class mainDraw extends JComponent {
public int x = 50;
public int y = 50;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(x, y, 50, 50);
g.fillRect(x, y, 50, 50);
g.setColor(Color.BLACK);
}
public void moveRight() {
x = x + 5;
repaint();
}
public void moveLeft() {
x = x - 5;
repaint();
}
public void moveDown() {
y = y + 5;
repaint();
}
public void moveUp() {
y = y - 5;
repaint();
}
}
BTW, use SwingUtilities
to put the gui update code because swing objects are not thread-safe.
Solution 2:
There are at least three issues...
Firstly...
Your mainFrame
class extends
from JFrame
, but in your main
method, you create an instance of it and ignore it, by creating your own JFrame
.
The KeyListener
is registered to the instance of mainFrame
, meaning, it's been ignored.
You should get rid of extends JFrame
as it's just confusing the issue
Secondly...
KeyListener
will only respond to key events when the component it is registered to is focusable AND has direct focus, this makes it unreliable.
Instead, you should use the key bindings API with the Draw
panel, this will allow you to over come the focus issues.
Thirdly...
You've broken the paint chain, this means that when the rectangle moves, what was painted previously will still remain.
You should refrain from overriding paint
and instead use paintComponent
. There are lots of reasons for this, but generally, it paints in the background, is called as updates to child components.
Finally, make sure you are calling super.paintComponent
before you do anything else, to ensure the Graphics
context is prepared for painting
Take a look at Performing Custom Painting for more details