
To keep things simple, you may use the Swing timer for the animation. However, if I were you I wouldn't move a JLabel. But instead I will draw directly onto the JPanel and keep a set of positions (x and y for the image). In the timer, update the position and repaint it.
Since you wanted to move a JLabel across the screen, you can do something like this:
class DrawingSpace extends JPanel{
private JLabel label;
private JButton button;
private Timer timer;
public DrawingSpace(){
setPreferredSize(new Dimension(200, 300));
initComponents();
add(label);
add(button);
}
public void initComponents(){
label = new JLabel("I am a JLabel !");
label.setBackground(Color.YELLOW);
label.setOpaque(true);
button = new JButton("Move");
//Move every (approx) 5 milliseconds
timer = new Timer(5, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
//Move 1 px everytime
label.setLocation(label.getLocation().x, label.getLocation().y+1);
}
});
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if(!timer.isRunning())
timer.start();
else
timer.stop();
}
});
}
}
Then the class to run the program:
class Mover{
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() { // Run the GUI codes on the EDT
@Override
public void run() {
JFrame frame = new JFrame("Some Basic Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawingSpace());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
If you plan to implement using paint()
, I would say you probably should be overriding paintComponents(Graphics g)
instead of paint(Graphics g)
from the Java Components.
Also do not clutter your paint method with things like Thread.sleep()
it may freeze your UI. The paint method should only contain codes needed for painting and nothing else.