I'm having trouble getting smooth and fluid motion with java Swing. Using this code, which involves using a BufferedImage to draw graphics to before applying it to the panel, gives me results with shaky motion and stuttering. How can I fix this?
public class SmoothMotion extends JPanel {
public static final int size = 800;
public static int pos = 0;
public static void main(String[] args) {
JPanel panel = new SmoothMotion();
JFrame frame = new JFrame("Smooth As");
frame.setSize(size, size);
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Timer timer = new Timer(17, new ActionListener() {
public void actionPerformed(ActionEvent e) {
SmoothMotion.updateItems();
panel.repaint();
}
});
timer.start();
}
public static void updateItems() {
pos += 4;
pos = pos > 750 ? 0 : pos;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, size, size);
g.setColor(Color.RED);
g.fillRect(pos > 375 ? 750 - pos : pos, 100, 50, 50);
}
}