so I made this image drawing class, when I press the a or d key the motion at first is very choppy but after a second or so it becomes kinda smooth. Why is this and how can I fix it?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
public class GameWindow extends JPanel {
Image map;
int x = 0, y = 0;
boolean isLeft = false, isRight = false;
Action left;
Action right;
Action hleft;
Action hright;
public GameWindow(BufferedImage map){
this.map = map.getScaledInstance(map.getWidth()*4, map.getHeight()*4, Image.SCALE_DEFAULT);
left = new Left();
right = new Right();
hleft = new HLeft();
hright = new HRight();
setFocusable(true);
requestFocus();
Timer t = new Timer(42, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
if(isLeft && !isRight){
x-=5;
} else if (!isLeft && isRight) {
x+=5;
}
repaint();
}
});
getInputMap().put(KeyStroke.getKeyStroke("pressed D"), "s move left");
getActionMap().put("s move left", left);
getInputMap().put(KeyStroke.getKeyStroke("pressed A"), "s move right");
getActionMap().put("s move right", right);
getInputMap().put(KeyStroke.getKeyStroke("released D"), "h move left");
getActionMap().put("h move left", hleft);
getInputMap().put(KeyStroke.getKeyStroke("released A"), "h move right");
getActionMap().put("h move right", hright);
t.start();
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(map, x, y, null);
}
public class Left extends AbstractAction{
@Override
public void actionPerformed(ActionEvent e) {
isLeft=true;
//System.out.println("TEST");
}
}
public class Right extends AbstractAction{
@Override
public void actionPerformed(ActionEvent e) {
isRight = true;
}
}
public class HRight extends AbstractAction{
@Override
public void actionPerformed(ActionEvent e) {
isRight = false;
}
}
public class HLeft extends AbstractAction{
@Override
public void actionPerformed(ActionEvent e) {
isLeft = false;
}
}
}
I tried searching what causes choppy motion, but the only thing that I could find was starting a timer instead of moving the image in the keybind / actionlistener, but It's still choppy
EDIT: I use Java 21.0.2, and I run Debian 12. I've contacted some friends, on some it runs smoothly (Windows, Arch) while on others (my pc and, Kali) it stutters.
I found the answer here: Why do my java graphics lag so much?
Apparently putting Toolkit.getDefaultToolkit().sync()
fixes the issue, although I'm not quite sure why.
Putting this here in case someone else stumbles into this issue.