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();} }
}
}
PSUnderwood - 19 Jul 2006 16:23 GMT
In actionPerformed, try this inside the for loop:
//mydrawpanel.repaint();
mydrawpanel.paint(mydrawpanel.getGraphics());
Regards,
Paul
> Hi,
>
[quoted text clipped - 74 lines]
> }
> }
Andrew Thompson - 19 Jul 2006 18:50 GMT
..
> 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.