Question

I am trying to move an label/icon & button from one place to another place using setLocation method but for some reason the objects are moving but not in motion. So if any one knows how to do this thing please tell me.

How to create a label or any component that moves from one place to another place in JFrame?

Below I have shown the code:

jl = JLabel
jf = JFrame

    public void actionPerformed(ActionEvent e) 
    {
        if(e.getSource()==jbtn)
        {
            for(int i=0;i<=30;i++)
            {
                jl.setLocation(100,100+i);
                jl.repaint();
                jf.repaint();
                try
                {
                    Thread.sleep(50);
                }
                catch(Exception ae)
                {
                    ae.printStackTrace();
                }
            }
        }
    }
Was it helpful?

Solution

Essentially you are blocking the thread (the Event Dispatching Thread) responsible for painting the updates

You might like to have a read of java timer change delay with button and Does displaying Java GUI requires some special treatment? which shows animation in swing and discusses the importance of the EDT.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top