error in simple animation

S

Sudhin

Hi,

The code to animate a cirlce works.but when i click the "click me"
button nothing happens.pls tell me why?

code is as follows:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;

public class animate implements ActionListener
{
int x=70;
int y=70;
int i;
JFrame frame;
drawpanel mydrawpanel;
JButton button;

public static void main (String[] args)
{
animate myanimation=new animate();
myanimation.go();
}

public void go()
{
frame=new JFrame("Click to animate");
mydrawpanel=new drawpanel();
button=new JButton();
button.setText("Click me");
button.addActionListener(this);
frame.getContentPane().add(BorderLayout.CENTER,mydrawpanel);
frame.getContentPane().add(BorderLayout.SOUTH,button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
for(i=0;i<130;i++)
{
x++;
y++;
mydrawpanel.repaint();

try{Thread.sleep(50);}


catch(Exception ex){} }
}

class drawpanel extends JPanel
{

public void paintComponent(Graphics g)
{
g.setColor(Color.white);
g.fillRect(0,0,this.getWidth(),this.getHeight());
g.setColor(Color.red);
g.fillOval(x,y,40,40);
}

}
public void actionPerformed(ActionEvent event)
{
x=70;y=70;
mydrawpanel.repaint();

for(i=0;i<130;i++)
{
x++;
y++;

mydrawpanel.repaint();
try{Thread.sleep(50);}


catch(Exception ex){ex.printStackTrace();} }
}
}
 
P

PSUnderwood

In actionPerformed, try this inside the for loop:

//mydrawpanel.repaint();
mydrawpanel.paint(mydrawpanel.getGraphics());

Regards,
Paul
 
A

Andrew Thompson

Sudhin wrote:
...
The code to animate a cirlce works.but when i click the "click me"
button nothing happens.pls tell me why?

That code is broken for a number of reasons.

1. Animated painting is best done in a Thread.
2. Time consuming operations should not done
within the actionPerformed method.

I suggest you go though the Sun Java2D examples at..
<http://java.sun.com/products/java-media/2D/samples/suite/index.html>
...especially..
<http://java.sun.com/products/java-media/2D/samples/suite/Colors/Balls.java>

Note that while the suggestion to 'getGraphics()' seems to
change the behaviour of this example to what you want, it
introduces other problems, and Sun advises against using
getGraphics().

Andrew T.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top