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!
You should add your listener in the mainDraw class, not your mainFrame.
It's a good practice not to handle key and mouse events in Frames and Windows.
o/
The rectangle is not moving because you are not using
JFrame
correctly. You have to assignframe
tonew mainFrame()
instead of ignoring the instantiatedmainFrame
object.There are several other issues as @MadProgrammer points out.
Here is the code that fixes some of the issues:
mainFrame.java
mainDraw.java
BTW, use
SwingUtilities
to put the gui update code because swing objects are not thread-safe.There are at least three issues...
Firstly...
Your
mainFrame
classextends
fromJFrame
, but in yourmain
method, you create an instance of it and ignore it, by creating your ownJFrame
.The
KeyListener
is registered to the instance ofmainFrame
, meaning, it's been ignored.You should get rid of
extends JFrame
as it's just confusing the issueSecondly...
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 usepaintComponent
. 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 theGraphics
context is prepared for paintingTake a look at Performing Custom Painting for more details
I was trying to implement shortcut listeners to whole frame and not succeeded, Finally found a way. If you want to set listener even when focus to another component, You must add listeners to all components.
Here is my code,
Call this in your constructor :
Method setShortcutListener(JFrame frame) :
Method getAllComponents(frame); Class Common is just a class,
Method getShortcutKeyListener() :
I think we have easy ways than this, But this code works exactly as expected. Key listeners works anywhere in form.
Hope this answer will help someone. Thanks.