I'm starting to paint squares in java and I use key listeners to move them. The only problem I seem to be having is, smooth transitions between moving from one direction to another. What I mean by this is, for example, when I move right then change my direction to left it stops for a second then starts moving again, but to the left. I'm trying to get a smooth transition to where when i switch from right to left it will instantly start going that direction instead of stopping, then going. Any help would be nice, thanks in advance :) !
My main frame class:
package mainpackages;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class Frame extends JFrame implements KeyListener{
Screen s;
public static void main(String[] args) {
new Frame();
}
public Frame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setTitle("Drawing practice");
setResizable(false);
setLocationRelativeTo(null);
addKeyListener(this);
init();
}
public void init() {
s = new Screen();
add(s);
setVisible(true);
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == e.VK_UP) {
s.y -= s.deltay;
}
if(e.getKeyCode() == e.VK_DOWN) {
s.y += s.deltay;
}
if(e.getKeyCode() == e.VK_LEFT) {
s.x -= s.deltax;
}
if(e.getKeyCode() == e.VK_RIGHT) {
s.x += s.deltax;
}
repaint();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
And my Screen class, where I paint the square to the JPanel
package mainpackages;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
public class Screen extends JPanel {
public static int x = 100;
public static int y = 100;
public static int deltax = 5;
public static int deltay = 5;
public Screen() {
}
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillRect(x, y, 50, 50);
}
}