I have created a program that creates a square and draws it on a JPanel. There are also KeyBindings that control the movement of the square (w is up) (s is down) (a is left) (d is right). My problem is that when I press the keys, it moves one instance, hesitates, then continues moving. Is there a way to prevent to the hesitation of the movement.
import javax.swing.JFrame;
public class MovingBox extends JFrame{
Panel panel;
public static void main(String args[]){
MovingBox mb = new MovingBox();
}
public MovingBox(){
super("Moving Box");
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new Panel();
add(panel);
setVisible(true);
}
}
This is my Panel class.
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Panel extends JPanel{
Rectangle box;
public Panel(){
box = new Rectangle(100, 100, 50, 50);
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "move left");
getActionMap().put("move left", new MoveAction(3, 3));
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "move right");
getActionMap().put("move right", new MoveAction(1, 3));
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "move up");
getActionMap().put("move up", new MoveAction(0, 3));
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "move down");
getActionMap().put("move down", new MoveAction(2, 3));
}
public void paintComponent(Graphics window){
super.paintComponent(window);
window.fillRect((int)box.getX(), (int)box.getY(), (int)box.getWidth(), (int)box.getHeight());
}
private class MoveAction extends AbstractAction{
int direction;
int speed;
public MoveAction(int direction, int speed){
this.direction = direction;
this.speed = speed;
}
public void actionPerformed(ActionEvent e){
if(direction == 0){
box.setLocation((int)box.getX(), (int)box.getY() - speed);
}else if(direction == 1){
box.setLocation((int)box.getX() - speed, (int)box.getY());
}else if(direction == 2){
box.setLocation((int)box.getX(), (int)box.getY() + speed);
}else if(direction == 3){
box.setLocation((int)box.getX() + speed, (int)box.getY());
}
repaint();
}
}
}
Any Help would be much appreciated. Thank You.