Solved

Cannot see intermediate steps in animation

Posted on 2011-02-28
7
962 Views
Last Modified: 2013-11-23
I am having trouble showing a simple animation in a Java application. I paint several circles separated by repaint and sleep requests but I only see the last one, not the intermediate ones. The attached code displays a single "circle" at (100,500). When the user clicks on the "Move" button I want it to show circles at (200,500), (300,500), and (400,500), separated by short delays. However I only see the last one. Probably a simple misconception on my part... Thanks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SlowExample{

    private Mypanel mypanel;
    private JButton button;

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                SlowExample eg = new SlowExample();
                frame.setContentPane(eg.createContentPane());
                frame.setSize(800, 800);
                frame.setVisible(true);
            }
          }
        );
    }

    public JPanel createContentPane(){
        JPanel contentPane = new JPanel(new BorderLayout()); 
                
        mypanel = new Mypanel();         
        contentPane.add(mypanel, "Center");

        button = new JButton("Move");
        button.addActionListener(new ButtonHandler(mypanel));
        contentPane.add(button, "South");
        
        return contentPane;
    }
} // end of class SlowExample

class ButtonHandler implements ActionListener {
    private Mypanel mypanel;
    public ButtonHandler(Mypanel mypanel) {
        this.mypanel = mypanel;
    }

    public void actionPerformed(ActionEvent e) {    
    	AbstractButton b = (AbstractButton) e.getSource();
        if (b.getText().equals("Move") ) {
            mypanel.move();
        } else 
        	System.err.println("Unknown source "+b.getText());
    }
} // end of ButtonHandler

class Mypanel extends JPanel{
    private Point p = new Point(100,500);

    public void paintComponent(Graphics g) { 
        super.paintComponent(g);
        int height = getSize().height;
        g.setColor(Color.red);
        g.fillOval(p.x-2, (height - p.y)-2, 8, 8);
    }

    public void move() {
    	p = new Point(200,500);
        repaint();
        try{Thread.sleep(500);} catch (InterruptedException e){};
    	p = new Point(300,500);
        repaint();
        try{Thread.sleep(500);} catch (InterruptedException e){};
        p = new Point(400,500);
        repaint();
    }     
} // end of Mypanel

Open in new window

0
Comment
Question by:reallygorgo
  • 4
  • 3
7 Comments
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 35003159
Swing is single threaded so you need to control your animation in a separate thread
http://helpdesk.objects.com.au/java/how-do-i-update-my-gui-from-any-thread
0
 

Author Comment

by:reallygorgo
ID: 35003375
I was afraid it was something like that. So does it make sense to think about spinning off a thread in my move method? I replaced my move method with the following, which seemed to work as I had hoped. Is there a better way? Can you explain what was going wrong  before? I guess I was sleeping the Event Dispatching thread?
public void move() {
    	Thread t = new Thread(new Runnable() {public void run() {    	
    		p = new Point(200,500);
    		repaint();
    		try{Thread.sleep(500);} catch (InterruptedException e){};
    		p = new Point(300,500);
    		repaint();
    		try{Thread.sleep(500);} catch (InterruptedException e){};
    		p = new Point(400,500);
    		repaint();}});
    	t.start();
    }

Open in new window

0
 
LVL 92

Expert Comment

by:objects
ID: 35003424
that looks better

> Can you explain what was going wrong  before? I guess I was sleeping the Event Dispatching thread?

correct. one thread handles updating the gui. so when you sleep no updates would occur.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 92

Expert Comment

by:objects
ID: 35003431
whether thats the best way or not depends on what you are ultimately trying to achieve.
How you have it currently it will spawn a new thread each time the button is pressed.
0
 

Author Comment

by:reallygorgo
ID: 35003465
wrong comment accepted
0
 

Author Closing Comment

by:reallygorgo
ID: 35003467
Thanks for your help.
0
 

Author Comment

by:reallygorgo
ID: 35003489
> How you have it currently it will spawn a new thread each time the button is pressed

I guess that a more conventional approach would be to organise things up front.. eg. along the lines of the Model-View-Controller pattern.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
what is the difference between "sudo su" and "su - root" 6 106
oracle 11g 23 50
Advice in Xamarin 21 57
Python 3.5.2 32 virtualenv problems 3 13
Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now