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:
Then the class to run the program:
If you plan to implement using
paint()
, I would say you probably should be overridingpaintComponents(Graphics g)
instead ofpaint(Graphics g)
from the Java Components. Also do not clutter your paint method with things likeThread.sleep()
it may freeze your UI. The paint method should only contain codes needed for painting and nothing else.