I want to create a small application.In my application I have jLabel1
and Jbutton1
. I want to animate jLabel1
from one side to another side using jButton
click. I don't know how to call it in the jButton1ActionPerformed
to create the animation of jLabel1
. I have done a paint application code which is giving as following.
Here is my code:
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2=(Graphics2D)g;
g2.drawString("ancd", x, y);
try {
Thread.sleep(10000);
} catch (Exception e) {
System.out.println(""+e);
}
x+=10;
if(x>this.getWidth())
{
x=0;
}
repaint();
}
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.