Well, I tried to make rectangular moving while typing arrows on Keyboard. It must work mostly like hitboxes
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
public class SHOWHITBOX extends JPanel implements KeyListener{
int move=0;
@Override
public void keyPressed(KeyEvent e) {
int key1 = e.getKeyCode();
if(key1==39){
move+=10;
System.out.println(move);
}
if(key1==37){
move-=10;
System.out.println(move);
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent arg0) {
}
public SHOWHITBOX(){
}
public void paintComponent(Graphics gr) {
gr.drawRect(move,400,1000,100);
gr.drawRect(move,400,100,100);
repaint();
}
}
It doesnt work, however Ive connected it to the class, and it annoys to the button typing (console output). But it still doesnt work. Second rect were did for test
There is two problems with your code:
Don't call repaint from paint* method, that would trigger too much unnecessary paint events. Much better is to call repaint at a time where you need the drawing to be made: for example inside methods that modifies the
movevariable.You are playing with a panel, so you need some mechanic to give it the focus. If not, it won't be able to receive the keyboard events. I forced the focus from the main requesting it from the window focus.
Here is the code:
Note that you must call
super.paintComponentin yourpaintComponentand that it is highly recommended to use the virtual keys symbols to test against the inputed keys.