How can I smooth the animation and still move fast?
One way is to draw translucent versions of a moving object along a path that it could have made if it had collected fewer pixels per turn.
eg. for a 10-pixel move, draw a version with an opacity of 10% for the first move pixel, 20% for the second, etc.

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MovingBlock { MovingBlock() { final JPanel gui = new JPanel() { private static final long serialVersionUID = 1L; int x = 0; int step = 60; public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; x+=10; Color fg = getForeground(); for (int ii=x-step; ii<x; ii+=4) { double transparency = (double)(x-ii)/(double)step; Color now = new Color( fg.getRed(), fg.getGreen(), fg.getBlue(), (int)(255*(1-transparency))); g2.setColor(now); g2.fillRect(ii, 3, 5, 10); } if (x>getWidth()) { x=0; } } }; gui.setBackground(Color.BLACK); gui.setForeground(Color.GREEN.darker()); gui.setPreferredSize(new Dimension(400,16)); ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { gui.repaint(); } }; Timer timer = new Timer(20, listener); timer.start(); JFrame f = new JFrame("Moving Block"); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.setContentPane(gui); f.pack(); f.setLocationByPlatform(true); f.setVisible(true); } public static void main(String[] args) throws Exception { SwingUtilities.invokeLater(new Runnable() { public void run() { new MovingBlock(); } }); } }
source share